The C library setvbuf() function is used to control the buffering of a file stream. This function can set the buffering mode and optionally specify a buffer for the stream.
SyntaxFollowing is the C library syntax of the setvbuf() function −
int setvbuf(FILE *stream, char *buffer, int mode, size_t size);Parameters
This function accepts the following parameters −
The function returns 0 on success and a non-zero value on failure.
Example 1: Full Buffering with Custom BufferHere, we set a custom buffer of size 1024 bytes for full buffering. Data is written to the file when the buffer is full or the file is closed.
Below is the illustration of the C library setvbuf() function.
#include <stdio.h> int main() { FILE *file = fopen("example1.txt", "w"); if (!file) { perror("Failed to open file"); return 1; } char buffer[1024]; if (setvbuf(file, buffer, _IOFBF, sizeof(buffer)) != 0) { perror("Failed to set buffer"); return 1; } fputs("This is a test string.", file); fclose(file); return 0; }Output
The above code writes "This is a test string." to example1.txt when the file is closed.−
This is a test string.Example 2: No Buffering
Thie example disables buffering, meaning data is written to the file immediately.
#include <stdio.h> int main() { FILE *file = fopen("example3.txt", "w"); if (!file) { perror("Failed to open file"); return 1; } if (setvbuf(file, NULL, _IONBF, 0) != 0) { perror("Failed to set buffer"); return 1; } fputs("This is a test string.", file); fputs("This is another string.", file); fclose(file); return 0; }Output
After execution of above code,it writes "This is a test string.This is another string." to example3.txt immediately as each fputs call is made.
This is a test string.This is another string.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4