Szymon Lipiński
Szymon Lipiński

Reputation: 28664

Write file without system and hdd cache

How can I write something to a file in C++ without using system cache and drive cache? I just want to write exactly on the hdd regardless all the system cache settings.

Upvotes: 6

Views: 4296

Answers (3)

MSN
MSN

Reputation: 54634

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).

Upvotes: 5

villintehaspam
villintehaspam

Reputation: 8734

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.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799370

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.

Upvotes: 2

Related Questions