How to use setbuf() in C++

In C++, we can use the setbuf() function to set the internal buffer to be used for I/O operations by a stream.

It should be called after associating it with an open file before performing any input or output operations.

Syntax

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

stream

It represents a pointer to a FILE object that identifies an open stream.

buffer

It represents a pointer to a user allocated buffer, which may or may not be null.

If the buffer is not null, it should be of at least BUFSIZ bytes; else, buffering is turned off.

BUFSIZ is a macro constant that expands to an integral expression with the size of the buffer used by the setbuf() function.

Return value

The function returns None.

Required headers

The setbuf() function requires the following library to work properly.

#include <cstdio>

Code

Consider the following example, where we open two files for writing purposes (i.e., file1.txt and file2.txt).

#include <cstdio>
int main () {
char buffer[BUFSIZ];
FILE* fp1 = fopen ("file1.txt", "w");
FILE* fp2 = fopen ("file2.txt", "a");
setbuf ( fp1 , buffer );
fputs ("This sent to a buffered stream", fp1);
fflush (fp1);
setbuf ( fp2 , NULL );
fputs ("This sent to an unbuffered stream", fp2);
fclose (fp1);
fclose (fp2);
return 0;
}

Explanation

  • Stream of file1.txt is set to a user allocated buffer.

  • A writing operation is performed. The data is logically part of the stream and is written to the device when called the fflush() function.

  • The stream of file2.txt is set to unbuffered that will write the subsequent output operation to the device as soon as possible.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources