Why does the simple line-copying loop while ...

Q

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

✍: Guest

A
p> 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.)

2015-11-13, 461👍, 0💬