c / intermediate
Snippet
Customizing Stream Buffering with setvbuf
The setvbuf function allows manual control over how a file stream (like stdout) is buffered. You can choose between fully buffered (_IOFBF), line buffered (_IOLBF), or unbuffered (_IONBF). Disabling buffering ensures that data is written to the output device immediately, which is critical for logging systems.
snippet.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <stdio.h>int main() {// Disable buffering for stdout// Useful for real-time logging or debuggingif (setvbuf(stdout, NULL, _IONBF, 0) != 0) {perror("Failed to set buffering");}printf("This message appears immediately ");// No fflush(stdout) needed because buffering is offprintf("without waiting for a newline.\n");return 0;}
Breakdown
1
setvbuf(stdout, NULL, _IONBF, 0);
Changes stdout to unbuffered mode; NULL means use internal buffer allocation.
2
_IONBF
Constant indicating 'No Buffering'.
3
perror("Failed to set buffering");
Prints a standard error message if the buffering change fails.