在打开的文件句柄上调用 CloseHandle 是否也意味着 FlushFileBuffers?

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

我遇到了类似的代码(针对 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);

最后一部分让我觉得迂腐,因为我的印象是调用 CloseHandle 会将任何缓冲输出刷新到磁盘(类似于 fclose(FILE *),MSDN 上的 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 .

那么,在关闭文件句柄之前立即调用 FlushFileBuffers 是否有必要避免丢弃缓冲输出?

关闭句柄不会丢弃未刷新的更新,但也不会刷新它们。

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.

如果您不读取直接写入,则在关闭句柄之前或句柄生命周期的任何时候都不需要刷新。