Force formatting a file stream in Windows

I am using ofstream

to write data to a file. I regularly call flush

the file, but the support file is not always updated at this time. I am guessing it has to do with the OS layer cache or something inside the MSVC libraries.

I need the data to be properly cleared at this point. Preferably written to disk, but at least so much that a copy operation from another program will see all the data up to the flush point.

What API can I use for this?


source to share

4 answers

FlushFileBuffers will flush the Windows write cache and write it to a file. Remember that it can be very slow if you call it again.

I also found this KB article which describes the use of _commit (). This might be more helpful to you since you are using streamstream.





If this is a Windows only solution, you can use FlushFileBuffers()

. This means that you have to rewrite some of your code to place calls CreateFile()

, WriteFile()

etc. If your application depends on many different functions operator<<

, you can write your own std::streambuf


You can also read the remarks section carefully. In particular,

Due to interactions with disk caching within the system, the function FlushFileBuffers

may be ineffective when used after every write to the drive, where many writes are performed separately. If your application is doing multiple writes to disk and also needs to ensure that critical data is written to persistent media, the application should use unbuffered I / O instead of frequent calls FlushFileBuffers




I used:



I am using stl_port on Win 7 with ICC 9.1.

I haven't tested the solution extensively, but it seems to work ... Perhaps it can solve the problem of missing fd () seen by edA-qa mort-ora-y.



Just add commode.obj

to Linker-> Input-> Additional Dependencies on the project properties page in Visual Studio and call std::ostream::flush()

. This way std :: ostream flush will refer to another method that has the desired behavior. It helped me.



All Articles