prev up next   top/contents search

comp.lang.c FAQ list · Question 12.2

Q: Why does the simple line-copying loop while(!feof(infp)) { fgets(buf, MAXLINE, infp); fputs(buf, outfp); } copy the last line twice?

A: In C, end-of-file is only indicated after an input routine has tried to read, and failed. (In other words, C's I/O is not like Pascal's.) Usually, you should just check the return value of the input routine:

	while(fgets(buf, MAXLINE, infp) != NULL)
		fputs(buf, outfp);
In virtually all cases, there's no need to use feof at all. (feof, or more likely ferror, may be useful after a stdio call has returned EOF or NULL, to distinguish between an end-of-file condition and a read error.)

References: K&R2 Sec. 7.6 p. 164
ISO Sec. 7.9.3, Sec., Sec.
H&S Sec. 15.14 p. 382

prev up next   contents search
about this FAQ list   about eskimo   search   feedback   copyright

Hosted by Eskimo North