Search code examples
cwinapihandleio-buffering

Does calling CloseHandle on a file handle open for writing imply FlushFileBuffers too?


I encountered code similar to this (stripped down for MCVE):

HANDLE hFile = CreateFileW(argv[1], GENERIC_WRITE, 0, NULL, CREATE_ALWAYS,
    FILE_ATTRIBUTE_NORMAL, NULL); 
// Note: FILE_FLAG_NO_BUFFERING and FILE_FLAG_WRITE_THROUGH are not present
DWORD dwWritten;

WCHAR wBOM = 0xFEFF, wString[100] = L"Hello World!";

SetFilePointer(hFile, 0, NULL, FILE_BEGIN);
WriteFile(hFile, &wBOM, sizeof(WCHAR), &dwWritten, NULL);
WriteFile(hFile, wString, wcslen(wString) * sizeof(WCHAR), &dwWritten, NULL);

FlushFileBuffers(hFile);
CloseHandle(hFile);

The last part struck me as pedantic since I had the impression that calling CloseHandle would flush any buffered output to disk (similar to fclose(FILE *), where it is explicitly documented by the C Standard that buffers will be flushed). However, I wasn't able to find this information in the documentation for CloseHandle on MSDN.

So, is the call to FlushFileBuffers immediately before closing the file handle necessary to avoid discarding buffered output?


Solution

  • Closing the handle does not discard unflushed updates, but it does not flush them either.

    FlushFileBuffers() is useful if you want to force flushing before CloseHandle() because the latter does not flush the buffers automatically. However, if you really need direct writes, you must open the handle with FILE_FLAG_WRITE_THROUGH.

    If you do not read direct writes, then flushing is not necessary either before closing the handle or at any point of the life of the handle.