0

FILE *ptr;
char i;
ptr=fopen("file.c","r");
while((i=fgetc(ptr))!=Null)
printf("%c",i);


leads to infinite loop???

but
while(fgets(str,80,ptr)!=NULL)
puts(str);

on the similiar terms doesn't???

4
Contributors
3
Replies
4
Views
11 Years
Discussion Span
Last Post by Salem
0

FILE *ptr;
char i;
ptr=fopen("file.c","r");
while((i=fgetc(ptr))!=Null)
printf("%c",i);


leads to infinite loop???

but
while(fgets(str,80,ptr)!=NULL)
puts(str);

on the similiar terms doesn't???

Maybe because fgetc () returns EOF when end of file is reached or an error is encountered hence your loop never terminates while fgets ( ) returns NULL whenever it encounters End of file or an error.

So maybe something like while ((i = fgetc (ptr) != EOF) should do the job.

PS. It is generally not advisable to base your file reading loop on EOF since it has the prob of reading an extra record and then jumping out of the loop.

HOpe it helped, bye.

0

> while((i=fgetc(ptr))!=Null)
As well as the EOF thing, i should be an int, not a char.
It needs to be capable of storing all 256 possible values of char AND EOF (257 different values in total).

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.