gpt4 book ai didi

c++ - 如何在 ofstream 上进行 fsync?

转载 作者:IT老高 更新时间:2023-10-28 22:14:10 39 4
gpt4 key购买 nike

我想确保已将 ofstream 写入磁盘设备。这样做的可移植方式是什么(在 POSIX 系统上可移植)?

如果我在 read-only 附加模式中单独 open 文件以获取文件描述符并调用 fsync 是否可以解决问题它?像这样:

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

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

最佳答案

如果您能够使用 Boost,请尝试使用基于 file_descriptor_sink 的流,例如:

#include <boost/filesystem.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include <boost/iostreams/stream.hpp>
#include <unistd.h>

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

关于c++ - 如何在 ofstream 上进行 fsync?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/676787/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com