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?