How to do fsync on an ofstream?

Vik picture Vik · Mar 24, 2009 · Viewed 10.8k times · Source

I want to make sure that an ofstream has been written to the disk device. What's the portable way (portable on POSIX systems) of doing this?

Does that solve the problem if I open the file separately in read-only append mode to get a file descriptor and call fsync with it? Like this:

ofstream out(filename);
/* ...
   write content into out
   ...
*/
out.close();

int fd = open(filename, O_APPEND);
fsync(fd);
close(fd);

Answer

mrtimdog picture mrtimdog · May 23, 2014

If you're able to use Boost, try a file_descriptor_sink based stream, eg.:

boost::filesystem::path filePath("some-file");
boost::iostreams::stream<boost::iostreams::file_descriptor_sink> file(filePath);

//  Write some stuff to file.

//  Ensure the buffer's written to the OS ...
file.flush();

//  Tell the OS to sync it with the real device.
//
::fdatasync(file->handle());