I'm using an ofstream
to write data to a file. I regularly call flush
on the file but the backing file doesn't always get updated at that time. I assume this is related to an OS-level cache, or something inside the MSVC libraries.
I need a way to have the data properly flush at that point. Preferably written to disc, but at least enough such that a copy operation from another program would see all data up to the flush point.
What API can I use to do this?
FlushFileBuffers will flush the Windows write file cache and write it to a file. Be aware it can be very slow if called repeatedly.
I also found this KB article which describes the use of _commit(). This might be more useful to you since you are using ofstream.
Just add
commode.obj
to Linker->Input->Additional Dependencies in the project's Property Pages in Visual Studio and callstd::ostream::flush()
. That way std::ostream's flush will link against another method which has the desired behavior. That's what helped to me.If this is a windows-only solution, you might want to use
FlushFileBuffers()
. This means you will have to re-write some of your code to accomodate calls toCreateFile()
,WriteFile()
, etc. If your application depends on many differentoperator<<
functions, you can write your ownstd::streambuf
.You also might want to read the remarks section carefully. In particular,
I used:
I'm using stl_port on Win 7 with ICC 9.1.
I have not tested the solution extensively but it seems to work... Maybe it could solve the problem of the absence of fd() noticed by edA-qa mort-ora-y .