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
This will not work the way you expect:
getc()
returns the character read, which can beEOF
, butfscanf()
returns the number of input items assigned, orEOF
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:
Or:
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, becausec
will always be converted to a positive int (again, only in platforms with unsigned chars), and thus will never be equal toEOF
. If you check the manpages forgetc()
andputc()
(and other functions that deal with a character), you will see that they receiveint
, notchar
.