fclose

 

Description

The fclose function closes stream.

Syntax

int fclose( FILE * stream )

Parameters

stream
Pointer to FILE structure ( must be non-null pointer )

Return

fclose returns 0 if the stream is successfully closed. It return EOF to indicate an error.

Examples

EX1

//The following example opens a file named "data.txt" and "data2.txt". It then uses 
//fclose to close "data.txt" and "data2.txt"

void test_fclose()
{
    FILE *stream, *stream2;
    
    // Open for read (will fail if file "data" does not exist)
    stream  = fopen( "c:\\data.txt", "r" );
    if( stream == NULL )
        printf( "The file 'data' was not opened\n" );
    else
        printf( "The file 'data' was opened\n" );
    
    // Open for write 
    stream2 = fopen( "c:\\data2.txt", "w+" );
    if( stream2 == NULL )
        printf( "The file 'data2' was not opened\n" );
    else
        printf( "The file 'data2' was opened\n" );
    
    // Close stream 
    if ( stream != NULL )
    {
        if( fclose( stream ) )
            printf( "The file 'data' was not closed\n" );
        else
            printf( "The file 'data' was closed\n" );
    }
    // Close stream2 
    if ( stream2 != NULL )
    {
        if( fclose( stream2 ) )
            printf( "The file 'data2' was not closed\n" );
        else
            printf( "The file 'data2' was closed\n" );
    }
}

EX2

// If a code executed after opening the file and before closing it and the code excution leads
// to execution error, the file stays open. to avoid such circumstance, one may use a try catch block
// to assure the file is closed either way. plese check the following code
void test_file_process(FILE *ff2)
{
    FILE *ff;
    ff = fopen("C:\\MyFile3.txt", "w");
    fprintf(ff, "Hello World");
    try
    {
        fprintf(ff2, "Hello World");// ff2 is supplied by caller and could be junk
    }
    catch (int nErrorCode)
    {
        fclose(ff);
        
    }
    fclose(ff);
}
void test_error_handle()
{
    test_file_process(NULL);
}

Remark

The fclose function closes stream. All buffers associated with the stream are flushed prior to closing. System-allocated buffers are released when the stream is closed. Buffers assigned by the user with setbuf and setvbuf are not automatically released.

See Also

fflush, fopen

header to Include

origin.h

Reference