如何从ofstream获取文件描述符

问题描述 投票:0回答:1

我需要调用 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++ file descriptor fsync
1个回答
0
投票

从 C++ 2026 开始,我们有一种方法来检索系统文件句柄:

native_handle_type handle(tcfg.native_handle());

更多关于 native_handle()

在 Linux 和其他 Unices 上,您可能会获得文件描述符(

int
)。因此,就您的情况而言,您可以这样做:

fsync(tcfg.native_handle());
© www.soinside.com 2019 - 2024. All rights reserved.