i'm reading book c programming , don't understand shown example. or more precisely don't understand why works because think shouldn't.
the code simple, reads content of text file , outputs in output area. far understand it, think the
ch = fgetc(stream);
ought inside while loop, because reads 1 int time? , needs read next int after current 1 has been outputted. well, turns out code indeed works fine hope explain fallacy me. thanks!
#include <stdio.h> int main(int argc, char *argv[]) { file *stream; char filename[67]; int ch; printf("please enter filename?\n"); gets(filename); if((stream = fopen(filename, "r")) == null) { printf("error opening file\n"); exit(1); } ch = fgetc(stream); while (!feof(stream)) { putchar(ch); ch = fgetc(stream); } fclose(stream); }
i think confuse because of feof():
doc: int feof ( file * stream );
checks whether end-of-file indicator associated stream set, returning value different 0 if is.
this indicator set previous operation on stream attempted read @ or past end-of-file.
ch = fgetc(stream); <---"read current symbol file" while (!feof(stream)) { <---"check eof read/returned last fgetc() call" putchar(ch); <---"output lasts read symbol, not eof" ch = fgetc(stream); <---"read next symbols file" } <-- control reach here when eof found
a better way write loop like:
while((ch = fgetc(stream))!= eof){ <--" read while eof not found" putchar(ch); <-- "inside loop print symbol not eof" }
additionally, note: int fgetc ( file * stream );
returns character pointed internal file position indicator of specified stream. internal file position indicator advanced next character.
if stream @ end-of-file when called, function returns eof , sets end-of-file indicator stream (feof).
if a read error occurs, function returns eof , sets error indicator stream (ferror).
Comments
Post a Comment