[英]Terminal hangs when I run my program
Have written some code in unix which counts the number of words in argv[1] via a function. 用unix编写了一些代码,该代码通过一个函数计算argv [1]中的单词数。 The result is returned and displayed on stdout.
返回结果并显示在标准输出上。
When I run it, the process just keeps on going until I kill it. 当我运行它时,过程一直持续到我杀死它为止。 NO errors show or anything?
没有错误显示或什么? Would anyone mind just having a look.
有人介意看看吗?
THanks 谢谢
#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.