Utkan Gezer
Utkan Gezer

Reputation: 3069

freopen or freopen_s, what exactly are they doing?

errno_t freopen_s ( FILE** pFile, const char *path, const char *mode, FILE *stream );

Here, the freopen_s disassociates the FILE pointer stream from whatever it is pointing at, then associates it with the file that is located at path. The mode defines the limits for what could be done with this specific pointer stream.

As far as I can tell, all these are nothing different than what would happen with:

...
fclose( stream );
fopen_s( &stream, path, mode );
...

My question is: What does the pFile do there? freopen also has it, as the return value. From all the examples I have seen, pFile, after the call, also points at the same file that is located at path. So:

...
fclose( stream );
fopen_s( &stream, path, mode );
fopen_s( pFile, path, mode );
...

Is this really it?

Upvotes: 2

Views: 3849

Answers (1)

harper
harper

Reputation: 13690

When you continue reading the help that is referenced in your question you find the answer:

`freopen_s` is typically used to redirect the pre-opened files stdin, stdout, 
and stderr to files specified by the user.

So it is not intended that you use a self defined FILE pointer to freopen. Instead it affects the probably widely spreaded used stdout etc.

Regarding your question "Is this really it?": yes.

Edit: Regarding the other question: My question is: What does the pFile do there?

The pFile parameter to the function freopen_s is a pointer to a FILE*. The function can allocate a new FILE object an return the new pointer with pFile. There might be run-time libraries that doesn't allocate a new object but change the FILE structure that is passed indirectly by *pFile. But this is strongly implementation dependent.

Further the non-atomic operation may fail after the fclose part. In that case the run-time may change the pointer that is passed with pFile to NULL.

Upvotes: 1

Related Questions