C Standard Libraries C++

fflush()

Declaration

int fflush(FILE* qpStream);

Description

This function flushes the buffer of a buffered stream. The buffer for the argument "qpStream" is flushed when this function is called. If the function is successful and the buffer is flushed, the value zero is returned. Otherwise, the function returns EOF to indicate an error. A buffer for an output file stream is sent to the file, and a buffer for an input stream is simply cleared. Passing NULL into the function flushes all open output streams. Buffers are naturally flushed when they are filled, a file stream is closed, or if the program terminates.

Input File

fflush() Input File

Output File

fflush() Output File

Example

#include <cstdio>

int main()
{
    char* cpFileName = "XoaX.txt";
    FILE* qpFile = fopen(cpFileName, "r+" );

    // Verify that the file was opened.
    if (!qpFile) {
        printf("Could not open the file %s\n",  cpFileName);
        return 1;
    }

    // This writes over the first four bytes
    fputs("XoaX", qpFile);

    // Without this flush, fgets writes garbage to our file
    fflush(qpFile);

    char caBuffer[10];
    // Read the remaining bytes of the file into a buffer
    fgets(caBuffer, 5, qpFile);
    printf("Read in: %s\n", caBuffer);

    int iResult = ferror(qpFile);
    if (iResult != 0) {
        printf("Reading Error: %i\n", iResult);
        return 1;
    }

    fclose(qpFile);

    return 0;
}

Output

fflush() Output
 

© 2007–2024 XoaX.net LLC. All rights reserved.