tags:

views:

415

answers:

2

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);
+9  A: 

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.

In fact, doing the close() before the fclose() is guaranteed to make fclose() fail if there is any outstanding data to flush. (In a more general case, where the might be other code between the close() and fclose(), fclose() might simply write to the wrong file!)
Jonathan Leffler
+2  A: 

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.

Jason Coco