开发者

Write file without system and hdd cache

How can I write something to a file in C++ without using sys开发者_C百科tem cache and drive cache? I just want to write exactly on the hdd regardless all the system cache settings.


Unless you are writing a disk device driver, you can't guarantee that there won't be any cache or processing done with your write.

The C runtime library exposes fflush(FILE *) to do this. Windows has FlushFileBuffers as well as a flag you can pass to CreateFile (FILE_FLAG_NO_BUFFERING) (which itself adds restrictions on what you can do).

An alternative to trying to bypass write caching is to make your data structures resilient to partial failure. For files, one popular technique is to write out the header of the file after the rest of the file is written. Assuming Murphy and not Machiavellian behavior, that should be enough.

Or use the OS provided file replacement or transaction functions (See ReplaceFile and Transactional NTFS for Windows).


On Linux you can pass O_DIRECT to open(2) in order to try to avoid the OS cache, but you don't have the same level of control over the drive cache.


This is highly operating system dependent. On Windows you can specify FILE_FLAG_NO_BUFFERING when you open the file with CreateFile to disable system caching. You won't get around hard disk caching though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜