Input-output buffering (IO buffering) has been a part of the C language since the inception of the standard library (stdio). It was introduced to enhance the performance of read and write operations, as accesses to disks or devices are time-consuming operations, and buffering allows for a reduction in their frequency.
Misunderstanding how buffering works can lead to unexpected delays in input-output, data loss during abrupt program termination, errors when dealing with multiple threads (especially with stdout/stderr), and synchronization errors between processes or systems.
Knowing that file streams can be fully buffered, line buffered, or unbuffered, it is important to use functions for forced buffer flushing (fflush()), correctly close files (fclose()), and wisely combine the use of stdin, stdout, and stderr. Buffering also depends on the type of stream (for example, stdout flushes when a character is output in a terminal-connected stream, but not always—if it is a file).
Code example:
#include <stdio.h> int main() { printf("Hello"); // sleep(10); // output won’t occur until fflush fflush(stdout); // immediately outputs the buffer to the screen return 0; }
Key Features:
fflush() is the main tool for manually flushing the bufferCan you rely on the output of printf to appear on the screen immediately?
No, if the output is directed not to a terminal, but to a file, the lines will not appear until a buffer flush occurs or the buffer limit is reached. Even in a terminal, a line without a may not appear immediately. Use fflush(stdout); for immediate output.
What happens if you call fflush(stdin)?
This is undefined behavior according to the C standard. Some compilers/platforms may clear the input stream's buffer, but this is not guaranteed by the standard, and such a practice is non-portable and potentially dangerous.
Can printf and fprintf(stderr, ...) be considered equivalent for immediate output?
No. Standard output (stdout) is usually fully buffered or line buffered, while stderr is always unbuffered by standard. That means output to stderr appears on the screen immediately, but output to stdout does not.
fflush(stdin) to clear the input bufferA program writes to a log file via printf, but does not call fflush(stdout) and does not close the file during abrupt termination.
Pros:
Cons:
A program calls fflush(stdout) after each important log entry, or writes critical messages to stderr.
Pros:
Cons: