How C buffers I/O for speed
What you'll learn: How C uses a "waiting room" strategy called buffering to prevent slow hardware from dragging down your code's performance.
The Problem: The Slow Postal Worker
Imagine you are writing letters. Every time you finish a single sentence, you walk three miles to the post office to mail it. You would spend all day walking and almost no time writing. In computing, your CPU is the writer, and the Hard Drive (or SSD) is the post office. Communicating with hardware is incredibly slow compared to the lightning speed of your processor. If C sent every single character to the disk the moment you typed it, your programs would crawl.
The Solution: The Outbox
To fix this, C uses buffering. Instead of sending data immediately, C sets aside a small block of memory (a buffer) to act as a temporary "outbox."
When you call printf() or fprintf(), C doesn't usually talk to the hardware right away. It simply drops your data into the buffer. Once that buffer is full, or when you manually tell it to, C sends the entire chunk of data to the hardware in one single, efficient trip. This is like waiting until you have a full bag of mail before driving to the post office.
Buffering in Action
Standard output (stdout) is typically line-buffered. This means C holds onto your data until it sees a newline character (\n) or the program ends.
#include <stdio.h>
#include <unistd.h> // For sleep()
int main() {
// This text sits in the "outbox" (buffer)
printf("Loading data...");
// Pause for 2 seconds
sleep(2);
// The \n triggers a "flush," pushing everything to the screen at once
printf(" Done!\n");
return 0;
}
In the example above, you might notice that "Loading data..." doesn't appear on the screen immediately because there is no \n. It stays in the buffer until the second printf finishes the line.
If you absolutely must send data immediately without a newline, you can use fflush(stdout);. This forces C to empty the buffer and send the data to the hardware right now.
Key takeaway
Buffering saves time by grouping many small I/O operations into one large, efficient hardware update.