CC Explainer
C · 3 · Structs, Unions & I/O16 / 35 · 46%

stdio Buffering & errno

Why your printf didn't appear, and how to report real error causes.

Examples: setvbuf, fflush, errno, perror

shortcuts: ← prev · → next · M mark
1

Three Buffer Modes

stdout is line-buffered on a terminal, fully buffered into a pipe.

Syntax
syntax
setvbuf(stdout, NULL, _IONBF, 0);   // unbuffered
setvbuf(stdout, NULL, _IOLBF, 0);   // line buffered
setvbuf(stdout, NULL, _IOFBF, 4096);// fully buffered
WATCH OUT
If a program crashes before flushing, buffered output is lost — which is why prints "disappear" before a segfault. stderr is unbuffered on purpose.
2

fflush

Force the buffer out now.

Example
example
printf("working...");
fflush(stdout);       // appears immediately
long_running_task();
fflush(stdin) is undefined behavior — do not use it to clear input.
3

errno & perror

Library calls set errno on failure. Check the return value first, then read errno.

Example
example
#include <errno.h>
#include <string.h>

FILE *f = fopen("missing.txt", "r");
if (!f) {
    perror("fopen");                       // fopen: No such file or directory
    fprintf(stderr, "%s\n", strerror(errno));
    return 1;
}
4

errno Rules

errno is only meaningful right after a failure.

Common pitfalls
  • ✕Reading errno when the call succeeded — its value is stale garbage.
  • ✕Calling another library function before reading errno (it may overwrite it).
  • ✕Assuming errno is a plain global; it is thread-local in modern C.