Reputation: 9263
The signature for freopen is FILE * freopen ( const char * filename, const char * mode, FILE * stream )
According to the docs, the return value is the same as what stream
is set to. So, my code already checks stream != 0
, do I need to check the return value? How could stream == 0
but retval != 0
? If I don't need to check both, why does gcc give me a warning if I don't check the retval?
To quiet gcc, is it okay to simply do: stream = freopen(filename, mode, stream); if (!stream) {...})
?
Upvotes: 0
Views: 492
Reputation: 206717
You said:
According to the docs, the return value is the same as what stream is set to.
Not according to http://en.cppreference.com/w/c/io/freopen
Return value
1) A copy of the value of stream on success, null pointer on failure.
You asked:
do I need to check the return value?
Yes, you should, always. freopen
can fail for all the reasons that fopen
can fail -- permissions, non-existent directory, too many open files, etc. It is a good practice to always check the return value of freopen
before you use it.
Upvotes: 4
Reputation: 39060
If it fails, it's not going to magically set the original stream variable (which it has no reference to, since the parameter is FILE *
not FILE **
) to NULL, so you do need to check the return value.
Upvotes: 5