在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;
}
答案 0 :(得分:2)
当你的输入流中还有剩余的东西时,你正在循环,但你从来没有从循环内的输入流中实际读取,这意味着你的输入流是永远的,并且永远只是超过它的第一个字符,你的oTest
(第一个字符)永远不会改变。