2.1.9.4 fflush


Description

The fflush function flushes a stream.

Syntax

int fflush( FILE * stream )

Parameters

stream
Pointer to FILE

Return

fflush returns 0 if the buffer was successfully flushed. The value 0 is also returned in cases in which the specified stream has no buffer or is open for reading only. A return value of EOF indicates an error.

Note: If fflush returns EOF, data may have been lost due to a write failure.

Examples

EX1

void test_fflush()
{    
    FILE  *stream = fopen("C:\\text.txt", "w+" );
    if( NULL == stream )
    {
        printf("Failed to open file test.txt\n");
        return;
    }
    
    char input[6] = {'h', 'e', 'l', 'l', 'o'};
    
    fwrite( input, sizeof(char), 6, stream );  // Write a string into the file.
        
    fflush(stream);   
    fclose(stream);   //set a breakpoint at this line, use Windows Explorer to open the test.txt, you should be able to see that the string have been written to the file
}

Remark

The fflush function flushes a stream. If the file associated with stream is open for output, fflush writes to that file the contents of the buffer associated with the stream. If the stream is open for input, fflush clears the contents of the buffer. Also, fflush(NULL) flushes all streams opened for output. The stream remains open after the call. fflush has no effect on an unbuffered stream.

Buffers are normally maintained by the operating system, which determines the optimal time to write the data automatically to disk: when a buffer is full, when a stream is closed, or when a program terminates normally without closing the stream. The commit-to-disk feature of the run-time library lets you ensure that critical data is written directly to disk rather than to the operating-system buffers. Without rewriting an existing program, you can enable this feature by linking the program's object files with COMMODE.OBJ.

See Also

fclose

Header to Include

origin.h

Reference