3

for a FILE* stream, if I read as much data as possible, feof(stream) returns me non-zero. Then, If I fclose stream, it feof(stream) will continue to returns me a non-zero value? Is it GUARANTEED?

4 Answers 4

12

Calling feof() on a closed file is meaningless (actually worse than meaningless - it's undefined so anything can happen).

From the C standard:

The value of a pointer to a FILE object is indeterminate after the associated file is closed (including the standard text streams).

and

A successful call to the fclose function causes the stream pointed to by stream to be flushed and the associated file to be closed. Any unwritten buffered data for the stream are delivered to the host environment to be written to the file; any unread buffered data are discarded. Whether or not the call succeeds, the stream is disassociated from the file and any buffer set by the setbuf or setvbuf function is disassociated from the stream (and deallocated if it was automatically allocated).

3

Depending upon the library implementation, calling fclose() will result in deallocation of resources in the FILE structure and subsequent attempts may well result in a crash. I believe that the standard term for this is "undefined behaviour".

2

Don't do it. Don't try to run feof() on a closed file. The result is undefined. Keep track of which file handles are closed in some other way, rather than assuming EOF will be signaled on them.

In general, undefined behavior in C must must must MUST be avoided when writing portable code... it may do something sensible on your platform, but it may do something totally ridiculous or unexpected on another.

People on the Usenet group comp.lang.c came up years ago with a hypothetical computer, the DeathStation 9000, which exhibits the most frighteningly bad behavior in the case of undefined constructs. It's a sort of teaching tool to frighten you away from relying on undefined behavior in C :-)

1

Not for every implementation of feof().

In fact, you can't even guarantee that any f* call will work after you call fclose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.