I have function in C that assumes stdin is open. I want to add an assertion in front of it to make sure stdin is not closed by anyone. How can I check that stdin isn't closed by anyone?
assert(is_open(stdin));
You can't find out whether a FILE*
has been closed. fclose
might free
the FILE
object it points to, so that object's contents may be undefined after fclose
. This is true even of stdin
. The solution I proposed previously was wrong. Sorry about that.
The best you can do on a POSIX platform is something like
bool stdin_open()
{
errno = 0;
fcntl(STDIN_FILENO, F_GETFD);
return errno == EBADF;
}
though that really tells you something about the standard input FD, rather than the stdin
object.