tags:

views:

378

answers:

4

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?

+1  A: 

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".

Jon Trauntvein
+1  A: 

Not for every implementation of feof().

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

plinth
+8  A: 

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

Michael Burr
A: 

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 :-)

Dan