C++ setvbuf()

The setvbuf() function in C++ is used to change or specify the buffering mode and size of the buffer.

setvbuf() prototype

int setvbuf(FILE* stream, char* buffer, int mode, size_t size);

The setvbuf() function changes the buffering mode of the given file stream to the value of mode.

If the buffer is not null, the size of buffer is size, otherwise the function automatically allocates a buffer (based on value of size).

It is defined in <cstdio> header file.

setvbuf() Parameters

  • stream: A file stream.
  • buffer: Pointer to the buffer to be used by stream.
  • mode: Buffering mode. The types of buffering modes are:
    • _IOFBF: full buffering
    • _IOLBF: line buffering
    • _IONBF: no buffering
  • size: The size of buffer in bytes.

setvbuf() Return value

The setvbuf() function returns zero on success and nonzero on failure.

Example: How setvbuf() function works

#include <iostream>
#include <cstdio>

#define SIZE 1024

using namespace std;

int main()
{
    char buffer[SIZE] = "...";
    char str[] = "This is first line\nThis is second line";
    FILE *fp = fopen("test.txt","wb+");

    /* no buffering, buffer remains unchanged */
    setvbuf(fp,buffer,_IONBF,SIZE);
    fwrite(str, sizeof(str), 1, fp);
    cout << buffer << endl;

    /* line buffering, only a single line is buffered */
    setvbuf(fp,buffer,_IOLBF,SIZE);
    fwrite(str, sizeof(str), 1, fp);
    cout << buffer << endl;

    /* full buffering, all the contents are buffered */
    setvbuf(fp,buffer,_IOFBF,SIZE);
    fwrite(str, sizeof(str), 1, fp);
    cout << buffer << endl;

    fclose(fp);
    return 0;
}

When you run the program, the output will be:

...
This is second line
This is first line
This is second line