在 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
(第一个字符)永远不会改变。
关于c - 运行程序时终端挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21819078/