简体   繁体   中英

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.

all help is highly appreciated.

You forgot to test the result count of 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) ...). EOF is not a valid character (so by definition is outside of all the possible values of a 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 ). So the type of EOF is not char . And on my Linux/Debian/x86-64 that is happening.

Read much more carefully the documentation related to <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()

Yes, and in your case you'll better use fgetc . Again, read its documentation. It is very likely that fgetc is much faster (since more low-level) than fscanf . Most implementations of fscanf are using fgetc (or its equivalent).

At last, some C standard library implementations are free software . On Linux, both GNU glibc and musl-libc are. You could study their source code. You'll learn a lot by doing so. Both are built above Linux syscalls(2) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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