Full buffering vs Line buffering
What you'll learn: How the standard library groups small pieces of data together to make your programs run much faster.
The Post Office Analogy
Imagine you are writing letters to a friend. You have two ways to send them:
- Line buffering: Every time you finish a sentence and hit "Enter," you run to the post office to mail it.
- Full buffering: You write letters until your drawer is completely stuffed. Only when you can't fit another scrap of paper do you take the entire pile to the post office.
Communicating with hardware—like your hard drive or your monitor—is very slow compared to the speed of your CPU. To save time, C uses a buffer (a temporary storage area in memory) to collect data before sending it all at once.
Line Buffering: The Screen Default
By default, when you print to the screen (stdout), C uses line buffering. It waits until it sees a newline character (\n) before it actually pushes the text to your monitor. This is why if you print a prompt without a \n, it might not appear immediately until you call fflush() or the program ends.
Full Buffering: The File Default
When you write to a file, C switches to full buffering. It won't write to the disk every time you finish a line because disks are slow. Instead, it waits until the buffer (usually 4KB or 8KB) is completely full.
#include <stdio.h>
int main() {
// Writing to a file usually uses full buffering
FILE *fptr = fopen("log.txt", "w");
// This text stays in a memory buffer, NOT on the disk yet
fprintf(fptr, "This is a small amount of data.\n");
// The data is only "flushed" to the disk when:
// 1. The buffer gets full
// 2. We manually call fflush(fptr)
// 3. We close the file
fclose(fptr);
return 0;
}
Why does this matter?
If you are writing a high-performance program that logs millions of lines to a file, full buffering is a massive lifesaver. It reduces thousands of slow "disk trips" into a single, efficient batch. However, if your program crashes before the buffer is "flushed," you might lose the data that was sitting in memory.
Key takeaway
Line buffering sends data whenever a newline appears (common for screens), while full buffering sends data only when the memory limit is reached (common for files).