Question

It seems as though the following calls do what you'd expect (close the stream and not allow any further input - anything waiting for input on the stream returns error), but is it guaranteed to be correct across all compilers/platforms?

close(fileno(stdin));
fclose(stdin);
Was it helpful?

Solution

Nothing is guaranteed correct across every possible operating system. However, calling fclose(stdin) will work on any POSIX compliant operating system as well as Windows operating systems, so you should hit pretty much anything in general use at the moment.

As stated by the previous answer as well as my comment, there is no need to call close on the file handle. fclose() will properly close everything down for you.

OTHER TIPS

fclose(stdin) causes any further use of stdin (implicit or explicit) to invoke undefined behavior, which is a very bad thing. It does not "inhibit input".

close(fileno(stdin)) causes any further attempts at input from stdin, after the current buffer has been depleted, to fail with EBADF, but only until you open another file, in which case that file will become fd #0 and bad things will happen.

A more robust approach might be:

int fd = open("/dev/null", O_WRONLY);
dup2(fd, 0);
close(fd);

with a few added error checks. This will ensure that all reads (after the current buffer is depleted) result in errors. If you just want them to result in EOF, not an error, use O_RDONLY instead of O_WRONLY.

DO NOT DO a close on fileno(FILE*). FILE is a buffering object. Looking into its implementation and meddling with its state carries all the caveats and dangers that would come with similar misbehavior on any other software module.

Don't do it.

AGH. Seriously. Nasty.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top