feof()

I once debugged the following code ( twisted a bit )

#include <stdio.h>

#include <string.h>

#include <inttypes.h>

#include <errno.h>

void main(void)

{

FILE *fp = fopen("1.txt", "r");

fclose(fp);

while ( !feof(fp) ) {

char temp[128];

fread(temp, 1,1, fp);

printf("loop forever, %s\n", strerror(errno));

}

}

the loop never stops, with a print out of "Bad file descriptor" ( errno 9 ). so why feof() returns 0 ?

If you take a look at the implementation of feof() ( GNU implementation ), it simply set a flag to value 1 if "an file operation tries to go beyond the end of the file stream". Here, the key points are:

1. file stream must be a valid stream.

2. an operation happened that tried to access beyond the end of the stream.

Apparently, condition 1 was not met ( because we fclosed() it ) by the above code snippet, therefore feof() returns 0.

One can argue that nobody will do fread() after fclose() like the above. Well, in a multi-threaded environment, it can happen in a different thread.

What is the significance of the above? it means that feof() is not meant for error checking. It does not detect any error during file operation.

As a matter of fact, in all the code snippet inside C99, feof() is always combined with ferror() to detect if we hit "end of file, or just hit an error".

the correct code should be:

while ( !feof(fp) && !ferror(fp) )

instead of:

while ( !feof(fp) ) {