W## OS Page Cache
hen you call fwrite, the data you write doesn’t immediately go to disk. Instead, it is typically buffered in memory by the operating system or application library. Here’s what happens in detail:
1. The Write Buffer
When you call fwrite:
- Data is copied from your program’s memory into a buffer managed by the C library (e.g.,
stdio). - The buffer is typically a chunk of memory that accumulates write operations to improve performance by reducing the number of I/O syscalls. This means:
- The data is not immediately written to the disk file.
- It remains in memory until the buffer fills up or is explicitly flushed.
2. Flushing with fflush
If you want to ensure data is written to the file immediately:
- Call
fflush(file_pointer). - This instructs the library to write all buffered data for the file to the underlying file descriptor using the
write()syscall. However, this doesn’t guarantee the data is physically written to disk yet. It ensures that the data reaches the OS Page Cache
Ensuring Data Reaches Disk
To force data to be written from the page cache to disk you need to call fflush followed by fsync
FILE *file = fopen("data.txt", "w");
fwrite(data, sizeof(data), 1, file); // Write to buffer
fflush(file); // Flush to OS page cache
fsync(fileno(file)); // Force flush to disk
fclose(file); // Close the file