1
已經在unix中編寫了一些代碼,它通過函數來計算argv [1]中的單詞數。結果將返回並顯示在stdout上。當我運行我的程序時,終端掛起
當我運行它時,這個過程只是繼續下去,直到我殺了它。沒有錯誤顯示或任何東西?有人會介意只是看看。
感謝
#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;
}
你可能在'while(oTest!= 0)'時發生無限循環,因爲你永遠不會爲'oTest'重新分配一個值 – Jordan
學習如何使用'gdb'調試器**(https: //sourceware.org/gdb/download/onlinedocs/gdb/index.html) –