### freopen -- Redirect Open Files

Format

>     #include <stdio.h>
>     FILE *freopen(const char *filename, const char *mode, FILE *stream);

Language Level: ANSI, POSIX, XPG4
freopen closes the file currently associated with stream and reassigns stream to the file specified by filename. The freopen function opens the new file associated with stream with the given mode, which is a character string specifying the type of access requested for the file. You can also use the freopen function to redirect the standard stream files stdin, stdout, and stderr to files that you specify.

If filename is an empty string, freopen closes and reopens the stream to the new open mode, rather than reassigning it to a new file or device. You can use freopen with no file name specified to change the mode of a standard stream from text to binary without redirecting the stream, for example:

> `fp = freopen("", "rb", stdin);`

You can use the same method to change the mode from binary back to text.

Portability Note: This method is extension to the ANSI/ISO C standard.

See fopen -- Open Files for a description of the mode parameter.

Return Value
freopen returns a pointer to the newly opened stream. If an error occurs, freopen closes the original file and returns a NULL pointer value.

Example
This example closes the stream1 data stream and reassigns its stream pointer. Note that stream1 and stream2 will have the same value, but they will not necessarily have the same value as stream.

    #include <stdio.h>
    #include <stdlib.h>

    #if (1 == __TOS_OS2__)
      #define FILENAME "myfile.dat"  /*OS/2 filename*/

    #endif

    int main(void)
    {
       FILE *stream, *stream1, *stream2;
       stream = fopen("FILENAME","r");
       if (NULL == (stream2 = freopen("", "w+", stream1)))
            return EXIT_FAILURE;
       fclose(stream2);
       return 0;
    }

close -- Close File Associated With Handle
fclose -- Close Stream
_fcloseall -- Close All Open Streams
fopen -- Open Files
open -- Open File
_sopen -- Open Shared File
<stdio.h>