FlushFileBuffers

The FlushFileBuffers function flushes any buffers for the specified file and causes any buffered data to be written to a storage device. This function is useful for ensuring that critical data is written to disk.

BOOL FlushFileBuffers(
    HANDLE hFile // A handle to the file whose buffers are to be flushed.
);

Parameters

hFile
A handle to the file whose buffers are to be flushed. The handle must have been created with the GENERIC_READ or GENERIC_WRITE access rights.

Return Value

If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error information, call GetLastError.

Remarks

When you write data to a file, the system may keep the data in memory buffers to improve performance. The FlushFileBuffers function ensures that all buffered data for the specified file is written to disk. This is important for applications that need to guarantee that data is persistently stored, such as log files or transaction records.

This function returns as soon as the buffered data has been committed to the storage device. It does not wait for the write operation to complete.

For network shares, this function flushes buffers to the server, but it does not guarantee that the data has been committed to the server's storage device.

Example

The following C++ code demonstrates how to use FlushFileBuffers:


#include <windows.h>
#include <iostream>

int main() {
    HANDLE hFile = CreateFile(
        L"my_data.txt",
        GENERIC_WRITE,
        0,
        NULL,
        CREATE_ALWAYS,
        FILE_ATTRIBUTE_NORMAL,
        NULL
    );

    if (hFile == INVALID_HANDLE_VALUE) {
        std::cerr << "Error creating file: " << GetLastError() << std::endl;
        return 1;
    }

    const char* data = "This is some data to write.\n";
    DWORD bytesWritten;

    if (!WriteFile(hFile, data, strlen(data), &bytesWritten, NULL)) {
        std::cerr << "Error writing to file: " << GetLastError() << std::endl;
        CloseHandle(hFile);
        return 1;
    }

    std::cout << "Data written to buffer." << std::endl;

    // Flush the file buffers to ensure data is written to disk
    if (!FlushFileBuffers(hFile)) {
        std::cerr << "Error flushing file buffers: " << GetLastError() << std::endl;
    } else {
        std::cout << "File buffers flushed successfully." << std::endl;
    }

    CloseHandle(hFile);
    return 0;
}
                

Requirements

Minimum supported client Windows XP Professional
Minimum supported server Windows Server 2003
Header FileAPI.h (include FileAPI.h)
Library Kernel32.lib
DLL Kernel32.dll

See Also