difference between getc and fscanf

假如想象 提交于 2019-12-23 00:50:13

问题


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.



来源:https://stackoverflow.com/questions/21645857/difference-between-getc-and-fscanf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!