🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →C File Buffering Explained
Why a file can still be empty right after fputs, what fflush and fclose really do, how to switch buffering off with setvbuf, and why this matters for logging in embedded C programming.
File buffering in C is the reason a program can write a line, look at the file, and find nothing there. The standard library collects your output in a block of memory and sends it to the operating system later. This is a deliberate speed optimisation, but it surprises every beginner and it can cost you log lines when a device crashes. In this lecture of our free C programming course you will measure the effect with a real program, learn when data is flushed, and learn how to control it. It is a key topic for anyone taking a free embedded C course and writing field loggers.
What You Will Learn
- What file buffering in C is and why the library uses a stream buffer
- The three buffering modes: full, line and none
- When data actually leaves the buffer
- How to use
fflushandsetvbuf - The difference between flushing to the kernel and reaching the disk
- Logging strategies for embedded Linux devices
Prerequisites
Lectures 1 and 2 of this chapter. You should know how to open and close a file and check fopen for failure.
What Is File Buffering in C?
A buffer is an area of memory that holds data temporarily on its way to or from a file. When you open a stream, the library associates a buffer with its FILE *. Whatever you write goes into that buffer first. Only when the buffer is full, when you ask for it, or when the file is closed does the library hand the bytes to the operating system.
Why buffering exists
Each system call and each trip to a storage device is expensive. If you wrote a log one byte at a time without a buffer, you would pay that cost for every byte. With a buffer, many small writes are gathered and sent as one large block, so the number of expensive operations drops sharply. The buffer size is chosen by the library; the constant BUFSIZ from stdio.h gives a typical size and is 8192 on the test system used here.
The Three Modes of File Buffering in C
| Mode | Constant | When data is sent on | Typical stream |
|---|---|---|---|
| Fully buffered | _IOFBF | Buffer is full, or flush, or close | Regular files; stdout redirected to a file or pipe |
| Line buffered | _IOLBF | A newline is written, or buffer full | stdout connected to a terminal |
| Unbuffered | _IONBF | Immediately on every call | stderr |
This explains a puzzle you may already have met: a printf without a newline may not show up on the screen until later, and when you redirect a program’s output to a file, the order of stdout and stderr messages can change, because stderr is never held back.
File Buffering in C: Watching the Buffer Work
The program below asks the filesystem for the real file size after each step. It uses stat, which asks the kernel and therefore only sees bytes that already left the stream buffer.
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
static long on_disk(const char *path)
{
struct stat st;
return stat(path, &st) == 0 ? (long)st.st_size : -1L;
}
int main(void)
{
printf("BUFSIZ on this system = %d\n\n", BUFSIZ);
/* 1. default buffering (fully buffered for a regular file) */
FILE *fp = fopen("buf.txt", "w");
if (fp == NULL) { perror("buf.txt"); return EXIT_FAILURE; }
fputs("sensor=42\n", fp);
printf("after fputs : %ld bytes on disk\n", on_disk("buf.txt"));
fflush(fp);
printf("after fflush : %ld bytes on disk\n", on_disk("buf.txt"));
fputs("second=7\n", fp);
printf("after 2nd fputs : %ld bytes on disk\n", on_disk("buf.txt"));
fclose(fp);
printf("after fclose : %ld bytes on disk\n\n", on_disk("buf.txt"));
/* 2. switch buffering off before the first write */
fp = fopen("nobuf.txt", "w");
if (fp == NULL) { perror("nobuf.txt"); return EXIT_FAILURE; }
setvbuf(fp, NULL, _IONBF, 0);
fputs("sensor=42\n", fp);
printf("unbuffered fputs : %ld bytes on disk\n", on_disk("nobuf.txt"));
fclose(fp);
return EXIT_SUCCESS;
}
$ gcc -Wall -Wextra -std=c11 -D_POSIX_C_SOURCE=200809L -o buf_demo buf_demo.c
$ ./buf_demo
BUFSIZ on this system = 8192
after fputs : 0 bytes on disk
after fflush : 10 bytes on disk
after 2nd fputs : 10 bytes on disk
after fclose : 19 bytes on disk
unbuffered fputs : 10 bytes on disk
Reading the result
- After the first
fputsthe file is still empty: all 10 bytes are in the buffer. fflushforces the buffer out, so the file jumps to 10 bytes.- The second line (9 bytes) is buffered again, so the size stays at 10 until
fclosesends it, giving 19. - With
_IONBFthe data appears immediately, at the price of one system call per write.
When Is the Buffer Flushed?
| Event | Flushes the buffer? |
|---|---|
| The buffer fills up | Yes, automatically |
You call fflush(fp) | Yes, on demand |
You call fclose(fp) | Yes, before closing |
Program returns from main or calls exit | Yes, all open streams are flushed |
| Line buffered stream gets a newline | Yes |
| Program crashes, is killed, or power is cut | No, buffered data is lost |
Program calls _exit or abort | No guarantee |
Controlling Buffering with fflush and setvbuf
fflush
int fflush(FILE *stream); writes pending output of that stream to the operating system and returns 0 on success. Calling fflush(NULL) flushes every open output stream. Use it after writing a record you cannot afford to lose, or before a long operation. Do not call it on an input stream; the result is not defined by the C standard.
setvbuf
int setvbuf(FILE *stream, char *buf, int mode, size_t size); sets the mode and optionally supplies your own buffer. Call it right after fopen and before any read or write. Passing NULL for buf lets the library allocate one. This is useful when you want line buffering on a log file or a large custom buffer for bulk transfers.
FILE *log = fopen("app.log", "a");
if (log != NULL) {
setvbuf(log, NULL, _IOLBF, 0); /* flush at every newline */
fprintf(log, "boot ok\n"); /* appears in the file now */
fclose(log);
}
fflush is not fsync
fflush only moves data from your program’s buffer to the kernel. The kernel may still hold it in memory for a while. If power can fail, also call fsync(fileno(fp)) (declared in unistd.h) after fflush. This is POSIX, not standard C.
File Buffering in C: Performance and Reliability Trade-offs
| Strategy | Speed | Risk of losing data | Good for |
|---|---|---|---|
| Default full buffering | Best | High on crash | Bulk exports, offline processing |
| Line buffering | Good | Low (one line) | Application logs |
fflush after each record | Moderate | Low | Event records, counters |
fflush plus fsync | Slowest | Lowest | Critical settings on flash, power-loss safety |
| Unbuffered | Slow for small writes | Lowest in user space | Debug output |
Embedded Linux tip
Flash memory wears out with writes, so flushing every byte is harmful. Choose the weakest policy that meets your safety need: line buffering for ordinary logs, and an explicit flush plus fsync only for records that must survive a power cut.
Common Mistakes with File Buffering in C
- Checking a file with another tool right after writing and concluding the write failed. The data is still in the buffer.
- Not closing the file before the program is killed, so the tail of the log is missing.
- Calling
setvbufafter the first read or write; the behaviour is undefined. - Giving
setvbufa local array as the buffer and then returning from that function while the stream is still open. - Assuming
fflushguarantees the data is on the disk. - Using
fflush(stdin)to clear input, which is not valid standard C.
Best Practices
- Always
fclosefiles; closing is the safest flush. - Treat file buffering in C as a design decision: choose a mode on purpose instead of relying on defaults.
- Check the return value of
fflushandfclose: disk-full errors often show up there rather than atfopen. - Send diagnostic messages to
stderr, which is unbuffered. - Test your logger by killing the process with
kill -9and see what survives.
Key Takeaways
- File buffering in C means every stream has a buffer, so writes are not immediately in the file.
- Data leaves the buffer when it is full, flushed, or the file is closed.
- Terminals use line buffering, files use full buffering,
stderris unbuffered. fflushreaches the kernel;fsyncreaches the device.
Now that you understand how data is held and released, the next lecture of this free C tutorial covers the functions that start and end every file session: fopen with all its modes, and fclose.
Frequently Asked Questions
What is file buffering in C?
It is a block of memory attached to a stream that stores data temporarily so the library can read or write the file in large, efficient chunks.
Why is my file empty after fprintf?
The text is probably still in the stream buffer. It reaches the file after fflush, fclose, a full buffer, or normal program exit.
What does fflush do in C?
It sends any pending output of a stream to the operating system. It returns 0 on success and EOF on error.
How do I disable buffering in C?
Call setvbuf(fp, NULL, _IONBF, 0) right after opening the stream and before any I/O.
Is stderr buffered?
No. It is unbuffered by default, so error messages appear immediately.
Does fflush guarantee data is written to disk?
No. It hands data to the kernel. To push it to storage on POSIX systems, follow it with fsync(fileno(fp)).
Why do printf outputs appear late when redirected to a file?
Because stdout switches from line buffering (terminal) to full buffering (file or pipe), so output waits until the buffer fills or the program ends.
Master file handling in our free C programming course
Next lecture: fopen modes, error handling and fclose, explained with runnable examples.

2 Comments