Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flush disk write cache

When the policy for a disk in Windows XP and Vista is set to enable write caching on the hard disk, is there a way to flush a file that has just been written, and ensure that it has been committed to disk?

I want to do this programmatically in C++.

Closing the file does perform a flush at the application level, but not at the operating system level. If the power is removed from the PC after closing the file, but before the operating system has flushed the disk write cache, the file is lost, even though it was closed.

like image 948
selwyn Avatar asked Oct 06 '08 08:10

selwyn


3 Answers

.NET FileStream.Flush() will NOT flush the Windows cache for that file content; Flush() only flushes the .NET internal file buffer. In .NET 4.0, Microsoft fixed the problem by adding an optional parameter to Flush() which if set true causes FlushFileSystemBuffers to be called. In .NET 3.5 and below your only choice is to call FlushFileBuffers via pinvoke. See MSDN'sFileStream.Flush community comment for how to do this.

like image 179
jimvfr Avatar answered Nov 07 '22 04:11

jimvfr


You should not fix this at the time you close the file. Windows will cache, unless you open the file passing FILE_FLAG_WRITE_THROUGH to CreateFile().

You may also want to pass FILE_FLAG_NO_BUFFERING; this tells Windows not to keep a copy of the bytes in cache.

This is more efficient than FlushFileBuffers(), according to the CreateFile documentation on MSDN.

See also file buffering and file caching on MSDN.

like image 22
MSalters Avatar answered Nov 07 '22 05:11

MSalters


You haven't specified the development environment, so:

.Net

IO streams have a .Flush method that does what you want.

Win32 API

There is the FlushFileBuffers call, which takes a file handle as argument.

EDIT (based on a comment from the OA): FlushFileBuffers does not need administrative privileges; it does only if the handle passed to it is the handle for a volume, not for a single file.

like image 2
tzot Avatar answered Nov 07 '22 04:11

tzot