Forcing a write with fflush
What you'll learn: How to ensure your program displays text immediately by manually clearing the output buffer.
The Waiting Room
Imagine sending mail through a post office. Instead of driving to your house for every single letter, the mail carrier waits until their bag is full before making a trip. This is exactly how C handles output.
When you use printf, C doesn't usually send that text to the screen instantly. Instead, it stores the characters in a temporary "waiting room" called a buffer. The system usually waits for one of two things to happen before showing the text: the buffer gets full, or it encounters a newline character (\n). This is great for performance, but it can cause problems when you need text to appear now.
The Stuck Message
Imagine you are writing a loading bar or a prompt that stays on the same line. If you don't include a \n, your text might sit in the buffer indefinitely, leaving the user staring at a blank screen even though the code has already executed the printf command.
This is where fflush comes in. It acts like a "Send Now" button, forcing the system to empty the buffer and push everything to the destination immediately.
Using fflush
To use it, you call fflush() and tell it which "stream" to clear. For the standard output (your screen), we use stdout.
#include <stdio.h>
#include <unistd.h> // For the sleep function
int main() {
printf("Loading... ");
// Without the next line, "Loading..." might not show
// until the program finishes or the buffer fills up.
fflush(stdout);
// Simulate a long task
sleep(2);
printf("Done!\n");
return 0;
}
In this example, calling fflush(stdout) ensures the user sees "Loading..." the very moment the line is reached, rather than two seconds later when the program ends.
When to use it
You don't need fflush for every print statement. Use it specifically when:
- You are printing text without a newline (
\n). - You are creating interactive prompts where timing is critical.
- You are debugging a crash and want to ensure the last message was printed before the program died.
Key takeaway
Use fflush(stdout) to manually push data out of the temporary buffer and onto the screen immediately.