簡體   English   中英

運行程序時終端掛起

[英]Terminal hangs when I run my program

用unix編寫了一些代碼,該代碼通過一個函數計算argv [1]中的單詞數。 返回結果並顯示在標准輸出上。

當我運行它時,過程一直持續到我殺死它為止。 沒有錯誤顯示或什么? 有人介意看看嗎?

謝謝

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>

//function declaration
int countWords(char []);

int main(int argc, char* argv [])
{
  int words;

  //check 3 entered values
  if (argc != 3)
  {
    write(2,"Please enter 2 values. Seperated by Space \n", 44);
    exit(0);
  }

  words = countWords(argv[1]);
  printf("Words are %i \n", words);
  return 0;
}

//function to count words
int countWords(char a [])
{
  int counter, openStream, oTest;
  char letter;

  openStream = open(a,O_RDONLY);
  if (openStream < 0)
  {
    write(2, "Error opening specified file. \n", 32); 
    exit(1);
  }

  oTest = read(openStream, &letter, 1);
  while (oTest != 0)
  {
    if (oTest == -1)
    {
      write(2, "Error reading file \n",21);
      exit(2);
    } 
    if (oTest == '\n' || oTest == ' ')
    {
      counter++;
    }
  }
  close(openStream);
  return counter;
}

您正在循環,而輸入流中仍有剩余內容,但是您實際上從未從循環中的輸入流中讀取內容 ,這意味着您的輸入流永遠並且永遠都超過它的第一個字符,而oTest (第一個字符)從不變化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM