-->

difference between getc and fscanf

2019-06-07 17:17发布

问题:

why does the following code work fine:

#include<stdio.h>
int main()
{
     FILE *fp=fopen("input.txt","r+");
     char c;
     while((c=getc(fp))!=EOF)
     {
         printf("%c",c);
     }
     fclose(fp);
     return 0;
}

but this code gives an error 'segmentation fault, core dumped':

#include<stdio.h>
int main()
{
     FILE *fp=fopen("input.txt","r+");
     char c;
     while((c=fscanf(fp,"%c",&c))!=EOF)
     {
         printf("%c",c);
     }
     fclose(fp);
     return 0;
}

input.txt contains a space separated list of characters like: a b c d e f

回答1:

This will not work the way you expect:

while((c=fscanf(fp,"%c",&c))!=EOF)

getc() returns the character read, which can be EOF, but fscanf() returns the number of input items assigned, or EOF if there was a failure before any conversion took place.

You can't assign this return value to c, because the return value is not the character read (which you then try to print later).

You should try this instead:

while(fscanf(fp,"%c",&c) == 1)

Or:

while(fscanf(fp,"%c",&c) != EOF)

Which is equivalent to saying "As long as there is a character to read..."

Also, in the first case (the code where you use getc()), c should be int - you can have an infinite loop if the target platform uses unsigned chars, because c will always be converted to a positive int (again, only in platforms with unsigned chars), and thus will never be equal to EOF. If you check the manpages for getc() and putc() (and other functions that deal with a character), you will see that they receive int, not char.