MSDN Community – Windows API

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

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:

Related Topics

Copied to clipboard!