【发布时间】:2019-02-24 05:19:17
【问题描述】:
我正在尝试使用以下代码编写一个程序来计算文件中的行数..
#include <stdio.h>
int main(int argc,char *argv[])
{
if(argc!=2)
{
printf("invalid no. of arguments\nUsage:lc <FILENAME>\n");
return 1;
}
FILE *in=fopen(argv[1],"r");
char c;
int count=0;
fscanf(in,"%c",&c); //take the first character
while(c!=EOF)
{
if(c=='\n')
count++;
fscanf(in,"%c",&c);
}
fclose(in);
printf("TOTAL LINES:%d\n",count);
return 0;
}
我知道这可以通过使用 fgetc() 来实现,但我很想知道为什么 fscanf() 在这里不起作用。
非常感谢所有帮助。
【问题讨论】:
-
您的缩进错误且令人困惑。 fscanf 返回您忘记测试的项目计数。最后,特别是在 Linux 上,
stdin是 line 缓冲的。阅读how to debug small programs -
EOF不是char它是int。