File System Synchronization (Sync)
The Windows file system provides several APIs to ensure that data written to a file is reliably persisted to the underlying storage medium. Proper synchronization is crucial for data integrity, especially after power failures or system crashes.
Key Functions
FlushFileBuffers– Flushes the buffers of a file to disk.SetFileValidData– Marks a range of a file as valid without writing data.WriteFileExwithOVERLAPPEDandGetOverlappedResult– Asynchronous writes with optional synchronization.DeviceIoControlwithFSCTL_LOCK_VOLUMEandFSCTL_UNLOCK_VOLUME– Volume level sync.
Example: Using FlushFileBuffers
// Open a file for writing
HANDLE hFile = CreateFileW(
L"C:\\Temp\\log.txt",
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hFile == INVALID_HANDLE_VALUE) {
wprintf(L"CreateFile failed: %lu\\n", GetLastError());
return;
}
// Write data
const char* data = "Important log entry\\n";
DWORD written;
BOOL ok = WriteFile(hFile, data, (DWORD)strlen(data), &written, NULL);
if (!ok) {
wprintf(L"WriteFile failed: %lu\\n", GetLastError());
}
// Ensure data is persisted
if (!FlushFileBuffers(hFile)) {
wprintf(L"FlushFileBuffers failed: %lu\\n", GetLastError());
}
// Close handle
CloseHandle(hFile);
When to Use Synchronization
Use explicit synchronization when:
- Writing transaction logs or database files.
- Saving user settings that must survive crashes.
- Implementing custom file caching mechanisms.