简体   繁体   English

为什么我不能使用 fscanf() 从文件中读取连续字符?

[英]Why can I not use fscanf() to read consecutive characters from a file?

I am trying to write a program to count the number of lines in a file by using the following code..我正在尝试使用以下代码编写一个程序来计算文件中的行数..

#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;
}

I am aware that this can be achieved by using fgetc(), but I am curious to know why fscanf() doesn't work here.我知道这可以通过使用 fgetc() 来实现,但我很想知道为什么 fscanf() 在这里不起作用。

all help is highly appreciated.非常感谢所有帮助。

You forgot to test the result count of fscanf .您忘记测试fscanf的结果计数。 In particular, your program is completely wrong when the processed file is an empty one.特别是,当处理的文件是空文件时,您的程序完全错误。

while(c!=EOF)

That can never happen (after any fscanf(in,"%c",&c) ...).永远不会发生(在任何fscanf(in,"%c",&c) ... 之后)。 EOF is not a valid character (so by definition is outside of all the possible values of a char ). EOF不是有效字符(因此根据定义,它超出了char的所有可能值)。 For instance, on your system, char could be unsigned 8 bits, and EOF could be -1 ( EOF is documented -in §7.21.1 of the C11 standard - to be some negative int , not some char ).例如,在您的系统上, char可能是 8 位无符号,而EOF可能是 -1( EOF被记录在 -在 C11 标准的第 7.21.1 节中- 是一些负的int ,而不是一些char )。 So the type of EOF is not char .所以EOF的类型不是char And on my Linux/Debian/x86-64 that is happening.在我的 Linux/Debian/x86-64 上,这种情况正在发生。

Read much more carefully the documentation related to <stdio.h>更仔细地阅读与<stdio.h>相关的文档

In general, read the documentation of every function that you are using.通常,请阅读您正在使用的每个函数的文档。 And learnHow to debug small programs并学习如何调试小程序

this can be achieved by using fgetc()这可以通过使用 fgetc() 来实现

Yes, and in your case you'll better use fgetc .是的,在您的情况下,您最好使用fgetc Again, read its documentation.再次阅读它的文档。 It is very likely that fgetc is much faster (since more low-level) than fscanf .很可能fgetcfscanf快得多(因为更底层)。 Most implementations of fscanf are using fgetc (or its equivalent). fscanf大多数实现都使用fgetc (或其等价物)。

At last, some C standard library implementations are free software .最后,一些C 标准库实现免费软件 On Linux, both GNU glibc and musl-libc are.在 Linux 上,GNU glibcmusl-libc都是。 You could study their source code.你可以研究他们的源代码。 You'll learn a lot by doing so.这样做你会学到很多东西。 Both are built above Linux syscalls(2) .两者都构建在 Linux syscalls(2)之上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM