[Previous] [Contents] [Next]

freopen()

Reopen a stream

Synopsis:

#include <stdio.h>

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

Library:

libc

Description:

The open stream fp is closed, and the file specified by filename is opened, associating its stream with fp.

The mode is described in the description of the fopen() function.

Returns:

A pointer to the newly opened stream, or NULL if an error occurs (errno is set).

Examples:

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

int main( void )
{
    FILE* fp;
    int c;

    /* Reopen the stdin stream so it's reading
     * from "file" instead of standard input.
     */
    fp = freopen( "file", "r", stdin );

    if( fp != NULL ) {
        /* Now we can read from "file" using the
         * stdin functions like fgetchar()...
         */
        while( ( c = fgetchar() ) != EOF ) {
            fputchar( c );
        }

        fclose( fp );
        
        return EXIT_SUCCESS;
    }
    
    return EXIT_FAILURE;
}

Classification:

ANSI

Safety:
Cancellation point Yes
Interrupt handler No
Signal handler No
Thread Yes

See also:

errno, fclose(), fcloseall(), fdopen(), fopen()


[Previous] [Contents] [Next]