edA-qa mort-ora-y edA-qa mort-ora-y - 20 days ago 11
C++ Question

Force ofstream file flush on Windows

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?

Answer

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());