问题
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?
回答1:
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.
CXXFileBuf.flush();
_commit(CXXFileBuf.rdbuf()->fd());
回答2:
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 to CreateFile()
, WriteFile()
, etc. If your application depends on many different operator<<
functions, you can write your own std::streambuf.
You also might want to read the remarks section carefully. In particular,
Due to disk caching interactions within the system, the
FlushFileBuffers
function can be inefficient when used after every write to a disk drive device when many writes are being performed separately. If an application is performing multiple writes to disk and also needs to ensure critical data is written to persistent media, the application should use unbuffered I/O instead of frequently callingFlushFileBuffers
.
回答3:
I used:
MyOfstreamObject.rdbuf()->pubsync();
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 .
回答4:
Just add commode.obj
to Linker->Input->Additional Dependencies in the project's Property Pages in Visual Studio and call std::ostream::flush()
. That way std::ostream's flush will link against another method which has the desired behavior. That's what helped to me.
来源:https://stackoverflow.com/questions/4473064/force-ofstream-file-flush-on-windows