There is no specific call in C to determine whether a particular
FILE* is open: you just try an operation on it and check to see
if the operation failed with a code indicating the file is closed.
Or for your purposes, as one of the posters pointed out, just
go ahead and close it: you won't bomb if it is already closed.
As others have already said, there is no such guarantee in C; the
memory to which a FILE * points can be deallocated on fclose() and any
use of it (or formally even of the pointer) is undefined and can fail.
<OT> Even in SUS2 and 3, which are what I have to hand, [EBADF]
says "The file descriptor underlying stream is not valid." Note,
nothing about the _stream_ not being valid.
In SUS/POSIX, if you only close() the underlying fd but _not_ fclose()
the stdio stream, then at least operations that actually try to use
the underlying file seem guaranteed to reject with EBADF. said:
STDOUT on the other hand is not a FILE*; it is generally part of
an I/O extension in which STDOUT is a macro which evaluates to the
"underlying descriptor" number of C's FILE* stdout . File descriptor
numbers are not part of C itself; many operations with file descriptors
are formalized in POSIX.1 . The typical operation to close a
file associated with a file descriptor is close(). There is no
standardized specific call to find out whether a file descriptor is
open, but you can fstat() the descriptor and look to see whether
you received the error that indicates the descriptor is not open.
Or fcntl(,F_GETFL). Or lseek(,0,SEEK_CUR). The "low-level" I/O
operations are guaranteed to fail cleanly, no undefined behavior.
Note however that file descriptors can be and almost always are
reused. (Stdio FILE *'s also _can_ be reused, but only sometimes are.)
If you have a stale fd-number and test it before doing I/O, it may
have been reused by an open() (or socket() etc.) elsewhere in the
program, so your test mistakenly thinks it is "still open" but your
I/O does something almost certainly wrong. There is no adequate
alternative to remembering for yourself which files you have open.
- David.Thompson1 at worldnet.att.net