setvbuf()

Declaration

int setvbuf(FILE* qpStream, char* cpBuffer, int iMode, size_t qSize);

Description:

This function sets the buffer for the stream "qpStream" to the passed in buffer "cpBuffer." The argument "qSize" specifies the buffer size in the range [2, INT_MAXM] in bytes rounded down to the nearest even number. The mode parameter "iMode" must be one of the following values: _IOFBF, _IOLBF, or _IONBF, which stand for full buffer, line buffering and no buffering. Full buffering and line buffer modes use the buffer with the given buffer size and no buffering is used to indicate that no buffer is used, regardless of what is passed in. The function returns 0 to indicate success and -1 to indicate an error.

Example

#include <cstdio>

int main()
{
    char* cpFileName = "XoaX.txt";
    // Open an ASCII text file for reading.
    FILE* qpFile = fopen(cpFileName, "r");

    // Check that the file was opened successfully.
    if (!qpFile) {
        printf("Could not open the file %s\n",  cpFileName);
        return 1;
    }
    // The can be whatever size we like
    const size_t kqBufferSize = 100;
    char caBuffer[kqBufferSize];
    // Set the buffer for the file stream
    setvbuf(qpFile, caBuffer, _IOFBF, kqBufferSize);

    // Read from the file.
    char caRead[50];
    fscanf(qpFile, "%s", caRead);

    printf("String read: %s\n", caRead);

    fclose(qpFile);
    return 0;
}

Input File:

setvbuf() Input File

Output:

setvbuf() Output