If fclose(0) is called, does this close stdin?

后端 未结 4 906
既然无缘
既然无缘 2021-02-13 22:22

If fclose(0) is called, does this close stdin?

The reason why I\'m asking this is that for some reason, stdin is being closed in my application and I cannot figure out

4条回答
  •  野性不改
    2021-02-13 23:13

    The signature of fclose is this:

    int fclose ( FILE * stream );
    

    That means, fclose expects a pointer to FILE object. So if you pass 0, instead of a pointer, 0 would be understood as NULL pointer1. If its NULL pointer, how do you expect it to close stdin? It will not close. Use fclose(stdin), as stdin itself is a pointer to FILE object.

    I think you're confusing stdin with file-descriptor which is of integral type, and usually denoted as fd. Its true that fd of input stream is 0. So if you want to use fd (instead of FILE*), then you've to use close from .

    #include 
    int close(int fildes);
    

    That is, close(0) would close stdin.

    1 : It seems interesting that if you had passed 1 to fclose with the intention to close stdout, your code wouldn't even compile, and you would immediately see the problem with your code at compile-time itself. Now the question is, why would it not compile? Because unlike 0, 1 is not implicitly converted into pointer type. The compiler would generate message like "error: invalid conversion from ‘int’ to ‘FILE*’. See the error and line number here at ideone.

提交回复
热议问题