如何在ofstream上执行fsync? [英] How to do fsync on an ofstream?
本文介绍了如何在ofstream上执行fsync?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我要确保已将ofstream写入磁盘设备.什么是可移植的方式(可在POSIX系统上移植)?
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?
如果我以只读附加模式单独open
文件以获取文件描述符并使用它调用fsync
,是否可以解决问题?像这样:
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);
推荐答案
如果您可以使用Boost,请尝试基于file_descriptor_sink的流,例如:
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());
这篇关于如何在ofstream上执行fsync?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文