What is C File Buffering Explained- C Programming Course Online

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Chapter 11 · Lecture 3

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 fflush and setvbuf
  • 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.

Where your bytes wait before reaching the file
fputs / fprintf Stream buffer in your program write() system call Kernel page cache Storage device
fflush() moves data up to here fsync() pushes it further, to the device

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

ModeConstantWhen data is sent onTypical stream
Fully buffered_IOFBFBuffer is full, or flush, or closeRegular files; stdout redirected to a file or pipe
Line buffered_IOLBFA newline is written, or buffer fullstdout connected to a terminal
Unbuffered_IONBFImmediately on every callstderr

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 fputs the file is still empty: all 10 bytes are in the buffer.
  • fflush forces 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 fclose sends it, giving 19.
  • With _IONBF the data appears immediately, at the price of one system call per write.
File size seen on disk during the demo
fputs: 0 bytes fflush: 10 bytes fputs: 10 bytes fclose: 19 bytes

When Is the Buffer Flushed?

EventFlushes the buffer?
The buffer fills upYes, automatically
You call fflush(fp)Yes, on demand
You call fclose(fp)Yes, before closing
Program returns from main or calls exitYes, all open streams are flushed
Line buffered stream gets a newlineYes
Program crashes, is killed, or power is cutNo, buffered data is lost
Program calls _exit or abortNo 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

Warning: 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

StrategySpeedRisk of losing dataGood for
Default full bufferingBestHigh on crashBulk exports, offline processing
Line bufferingGoodLow (one line)Application logs
fflush after each recordModerateLowEvent records, counters
fflush plus fsyncSlowestLowestCritical settings on flash, power-loss safety
UnbufferedSlow for small writesLowest in user spaceDebug 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 setvbuf after the first read or write; the behaviour is undefined.
  • Giving setvbuf a local array as the buffer and then returning from that function while the stream is still open.
  • Assuming fflush guarantees the data is on the disk.
  • Using fflush(stdin) to clear input, which is not valid standard C.

Best Practices

  • Always fclose files; 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 fflush and fclose: disk-full errors often show up there rather than at fopen.
  • Send diagnostic messages to stderr, which is unbuffered.
  • Test your logger by killing the process with kill -9 and 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, stderr is unbuffered.
  • fflush reaches the kernel; fsync reaches 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.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →