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.
void setbuf(FILE* stream, char* buffer);
streamIt represents a pointer to a FILE object that identifies an open stream.
bufferIt 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.
BUFSIZis a macro constant that expands to an integral expression with the size of the buffer used by thesetbuf()function.
The function returns None.
The setbuf() function requires the following library to work properly.
#include <cstdio>
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;}
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.