WriteFile函數通常是將數據寫入到內部緩沖區,然后OS會定期將緩沖區中的數據寫入到磁盤。如果想在調用WriteFile之后,數據就立即寫入磁盤,有如下三種方法:
1. 調用FlushFileBuffers(hFile);
Flushes the buffers of a specified file and causes all buffered data to be written to a file.
BOOL FlushFileBuffers(
HANDLE hFile // open handle to file whose buffers are to be flushed
);
該函數會將指定文件的緩存數據寫入磁盤。
2. 在用CreateFile創建文件的時候,第6個參數使用標志
FILE_FLAG_WRITE_THROUGH
Instructs the operating system to write through any intermediate cache and go directly to disk. The operating system can still cache write operations, but cannot lazily flush them.
3. 關閉掉句柄
CloseHandle(hFile);