C <stdio.h> - setvbuf() Function
The C <stdio.h> setvbuf() function is used to change the buffering mode of the given file stream stream. In addition, the function allows to specify the mode and size of the buffer (in bytes). If buffer is a null pointer, the function automatically resizes the internal buffer to size. Otherwise, it instructs the stream to use the user-provided buffer of size size beginning at buffer.
This function should be called after the stream pointed to by stream is associated with an open file but before any input or output operation is performed on the stream.
Syntax
int setvbuf (FILE * stream, char * buffer, int mode, size_t size);
Parameters
stream |
Specify a pointer to a FILE object that identifies an open stream. | ||||||||
buffer |
Specify pointer to a buffer for the stream to use or null pointer to change size and mode only. | ||||||||
mode |
Specify a mode for file buffering. It can be one of the following macro constants:
| ||||||||
size |
Specify size of the buffer. |
Return Value
Returns 0 on success. Otherwise returns a non-zero value.
Example:
The example below describes the usage of setvbuf() function.
#include <stdio.h> #include <stdlib.h> int main() { char buf[50]; if(setvbuf(stdout, buf, _IOFBF, sizeof buf)) { perror("Failed to change the buffer of stdout"); return EXIT_FAILURE; } printf("Programming"); //The buffer contains "Programming" //but nothing is written to stdout yet fflush(stdout); //Now "Programming" is written to stdout if(setvbuf(stdout, NULL, _IONBF, 0)) { perror("Failed to change the buffer of stdout"); return EXIT_FAILURE; } printf(" is"); //" is" is written to stdout //there is no buffering if(setvbuf(stdout, buf, _IOLBF, sizeof buf)) { perror("Failed to change the buffer of stdout"); return EXIT_FAILURE; } printf(" fun."); //The buffer now contains " fun." //but nothing is written to stdout yet putchar('\n'); //stdout is line buffered //everything in the buffer is now written to //stdout along with the newline return EXIT_SUCCESS; }
The output of the above code will be:
Programming is fun.
❮ C <stdio.h> Library