C Library Function - setvbuf()
C Standard Library - <stdio.h>
Description
The C library function int setvbuf(FILE *stream, char *buffer, int mode, size_t size) defines how the stream should be buffered.
Declaration
Here is the declaration for the setvbuf() function.
int setvbuf(FILE *stream, char *buffer, int mode, size_t size)
Parameters
stream -- This is a pointer to a FILE object that identifies an open stream.
buffer -- This is the user-allocated buffer. If set to NULL, the function will automatically allocate a buffer of the specified size.
mode -- This specifies the mode of file buffering:
Mode | Description |
---|---|
_IOFBF | Full buffering: For output, data is written once the buffer is filled. For input, the buffer is filled when an input operation is requested and the buffer is empty. |
_IOLBF | Line buffering: For output, data is written when a newline character is encountered or the buffer is filled, whichever happens first. For input, the buffer is filled when an input operation is requested and the buffer is empty, until the next newline character is encountered. |
_IONBF | No buffering: No buffer is used. Each I/O operation is written immediately. The buffer and size arguments are ignored. |
- size -- This is the size of the buffer in bytes.
Return Value
The function returns 0 if successful, otherwise it returns a non-zero value.
Example
The following example demonstrates the use of the setvbuf() function.
#include <stdio.h>
#include <unistd.h>
#include <string.h>
int main()
{
char buff[1024];
memset(buff, '\0', sizeof(buff));
fprintf(stdout, "Enabling full buffering\n");
setvbuf(stdout, buff, _IOFBF, 1024);
fprintf(stdout, "This is tutorialpro.org\n");
fprintf(stdout, "This output will be saved to buff\n");
fflush(stdout);
fprintf(stdout, "This will appear while programming\n");
fprintf(stdout, "Finally, sleep for five seconds\n");
sleep(5);
return(0);
}
Let's compile and run the above program, which will produce the following result. Here, the program saves buffered output to buff until the first call to fflush(), then starts buffering output, and finally sleeps for 5 seconds. It will send the remaining output to STDOUT before the program ends.
Enabling full buffering
This is tutorialpro.org
This output will be saved to buff
This will appear while programming
Finally, sleep for five seconds