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
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.
CXXFileBuf.flush();
_commit(CXXFileBuf.rdbuf()->fd());
source to share
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 callsFlushFileBuffers
.
source to share