FlushFileBuffers

Synopsis

BOOL FlushFileBuffers(
    HANDLE hFile
);

Header

Windows.h

Parameters

ParameterTypeDescription
hFile HANDLE Handle to the open file or device. The handle must have been created with GENERIC_WRITE access.

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

FlushFileBuffers ensures that any data stored in the file or device's cache is written to the underlying hardware. It is typically used when you need to guarantee that data is physically stored, such as before a system shutdown or when working with removable media.

Flushing does not change the file pointer position. If the file is opened with the FILE_FLAG_NO_BUFFERING flag, the operation has no effect because data is already unbuffered.

Note: Flushing a network file may be a no‑op if the remote protocol does not support it.

Requirements

Minimum supported client: Windows 2000
Minimum supported server: Windows Server 2003

Header: Windows.h
Library: Kernel32.lib

Example

#include <windows.h>
#include <stdio.h>

int main()
{
    HANDLE hFile = CreateFileW(L"example.txt",
                               GENERIC_WRITE,
                               0,
                               NULL,
                               CREATE_ALWAYS,
                               FILE_ATTRIBUTE_NORMAL,
                               NULL);
    if (hFile == INVALID_HANDLE_VALUE) {
        wprintf(L"CreateFile failed: %lu\\n", GetLastError());
        return 1;
    }

    const char *data = "Hello, FlushFileBuffers!\\n";
    DWORD written;
    if (!WriteFile(hFile, data, (DWORD)strlen(data), &written, NULL)) {
        wprintf(L"WriteFile failed: %lu\\n", GetLastError());
        CloseHandle(hFile);
        return 1;
    }

    if (!FlushFileBuffers(hFile)) {
        wprintf(L"FlushFileBuffers failed: %lu\\n", GetLastError());
        CloseHandle(hFile);
        return 1;
    }

    wprintf(L"Data flushed successfully.\\n");
    CloseHandle(hFile);
    return 0;
}

Related Functions