How to flush file buffers when using boost::serialization?
I'm saving a file on an USB drive and need to make sure that it's complete开发者_运维百科ly written to avoid corruption in case the USB drive is not removed properly. Well I've done some research and it seems this is possible via calling the FlushFileBuffers Win32 function. But the problem is, I'm saving using boost::serialization and thus don't have access to the actual file HANDLE. I wonder what is the proper way to flush the file? Thanks!
Call ostream::flush on the output stream you created your archive object with:
// create and open a character archive for output
std::ofstream ofs("filename");
boost::archive::text_oarchive oa(ofs);
...
ofs.flush();
You could also just let the objects go out of scope which should flush everything:
{
// create and open a character archive for output
std::ofstream ofs("filename");
boost::archive::text_oarchive oa(ofs);
// going out of scope flushes the data
}
Note, you still need to properly unmount your USB device. Flushing the data just makes sure it gets from userland into the kernel, but the kernel can also do it's own buffering.
精彩评论