freopen Function (Macro)

stdio.h

FILE *freopen (const char *filename, const char *mode, FILE *stream);

Associates a new file with an open stream.

freopen substitutes the named file in place of the open stream. It closes stream, regardless of whether the open succeeds. In this implementation, freopen is implemented as macro which first calls fclose passing stream to it, then calls fopen passing filename and mode to it. Such implementation is not absolutely correct, because the address of the file descriptor structure may be changed after closing and reopening again (if a garbage collect occurs). This is not a problem in programs which uses freopen as in

f=freopen (name, mode, f);
but it might cause problems in programs which uses freopen as in
freopen (name, mode, f);
To solve this problem, freopen macro will always re-assign the variable f to a (eventually) new value, so both above examples will be correct (the only small problem is in fact that f must ultimately be an lvalue, i.e, a variable or something similar).

On successful completion, freopen returns the argument stream (possibly changed). In the event of error, it returns NULL.

Note: This function is usually used for redirecting terminal streams like stdout and stdin. This is not possible here, because terminal-associated streams are not implemented.


Uses: fclose, fopen