我需要调用 fsync() 来保护我的数据。你能帮我从 ofstream 获取文件描述符吗?
string tmpconfig("config.tmp");
ofstream tcfg(tmpconfig.c_str());
if(tcfg)
{
tcfgNV.compactPrint(tcfg);
tcfg.flush();
if(!tcfg.good())
{
tcfg.close();
::remove(tmpconfig.c_str());
cout << "Failed to write the main configuration file: " << topconfig << endl;
return false;
}
REPORT_INFO("Syncing the file: " << topconfig);
// TODO I need to call fsync() here to secure my data.
//tcfg.pubsync();
tcfg.close();
}
从 C++ 2026 开始,我们有一种方法来检索系统文件句柄:
native_handle_type handle(tcfg.native_handle());
更多关于 native_handle()。
在 Linux 和其他 Unices 上,您可能会获得文件描述符(
int
)。因此,就您的情况而言,您可以这样做:
fsync(tcfg.native_handle());