C++ setbuf()

The setbuf() function in C++ sets the internal buffer to be used for I/O operations by a stream.

setbuf() prototype

void setbuf(FILE* stream, char* buffer);

If the buffer is not null, it is equivalent to calling setvbuf(stream, buffer, _IOFBF, BUFSIZ).

If the buffer is null, it is equivalent to calling setvbuf(stream, NULL, _IONBF, 0). In this case the buffering is turned off.

It is defined in <cstdio> header file.

setbuf() Parameters

  • stream: A file stream.
  • buffer: A pointer to a buffer which may be null or not. If it is null, buffering is turned off, otherwise it should of at least BUFSIZ bytes.

setbuf() Return value

None

The below 2 examples illustrates the use of setbuf() function. Both of these programs use file operation. In the first example, buffer is set using the setbuf() to store the contents of the file internally.

In the next example, the statement setbuf(fp, NULL) turns off buffering. So in order to read the file content, fread() is used.

Example 1: How setbuf() function works

#include <iostream>
#include <cstdio>

using namespace std;

int main ()
{
    char str[] = "Buffered Stream";
    char buffer[BUFSIZ];
    
    FILE *fp;
    fp=fopen ("test.txt","wb");
    
    setbuf(fp,buffer);
    fwrite(str, sizeof(str), 1, fp);
    
    fflush(fp);
    fclose(fp);

    cout << buffer;
    
    return 0;
}

When you run the program, the output will be:

Buffered Stream

Example 2: setbuf() function with buffering turned off

#include <iostream>
#include <cstdio>

using namespace std;

int main ()
{
    char str[] = "Unbuffered Stream";
    char strFromFile[20];
    
    FILE *fp;
    fp=fopen ("test.txt","wb+");
    
    setbuf(fp,NULL);
    fwrite(str, sizeof(str), 1, fp);
    fflush(fp);
    
    /* We need to rewind the file pointer and read the file because 
    the data from test.txt isn't saved in any buffer */
    rewind(fp);
    fread(strFromFile, sizeof(strFromFile), 1, fp);
    
    fclose(fp);
    
    cout << strFromFile;
    return 0;
}

When you run the program, the output will be:

Unbuffered Stream
Did you find this article helpful?