我正在使用ofstream
实现一个函数来更新/etc/dns.conf
中的配置文件。但是在系统REBOOT之后我的文件是EMPTY(文件在那里但没有内容)。
我认为flush()会立即将内容同步到物理文件。但是我的实现出了点问题。请帮我在这里找到真正的问题。
基本上我用所需数据创建一个tmp文件/etc/dns.bak
,然后删除原始文件/etc/dns.conf
并将tmp文件重命名为/etc/dns.conf
(注意程序是以root身份运行所以所有文件权限在那里。)
遵循的步骤:
ofstream
打开tmp文件<<
运算符flush()
close()
std::remove
std::rename
由于我的代码库有更多的逻辑,我创建了一个与我正在使用的文件完全相同的代码段
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
std::vector<std::string> m_dnsData_;
// I'm running as root and /etc/dns.conf exists
std::string m_dnsPath_ = std::string("/etc/dns.conf");
std::string m_dnsBackup_ = std::string("/etc/dns.bak");
bool ReplaceFile() {
// Open the file in the backup path
std::ofstream dns_backup;
dns_backup.open(m_dnsBackup_.c_str());//default is ios::out
// add data to the file
for (auto& i : m_dnsData_) {
dns_backup << (i + std::string("\n"));
}
dns_backup.flush(); // to synchronize the data with the physical file
dns_backup.close(); // close the file
// remove the original
int rc = std::remove(m_dnsPath_.c_str());
if (rc) {
std::cout << "Error remove [DNS]..." << std::endl;
return false;
}
rc = std::rename(m_dnsBackup_.c_str(), m_dnsPath_.c_str());
if (rc) {
std::cout << "Error renaming [DNS]..." << std::endl;
return false;
}
}
int main() {
// vector is filled with the required configurations
m_dnsData_.push_back(std::string("some config 1"));
m_dnsData_.push_back(std::string("some config 2"));
if (ReplaceFile() == true) {
std::cout << "File created successfully!" << std::endl;
} else {
std::cout << "File creation failed!" << std::endl;
}
// I can see the correct contents here
system((std::string("cat ") + m_dnsPath_).c_str());
// Also can see the file has correct size and correct data
// using vi /etc/dns.conf
// Reboot the system after 15 seconds
// After reboot the file can be seen
// But "/etc/dns.conf" has no contents
return 0;
}
我找到了解决方案
在重启之前添加了sync()方法(您需要
unistd.h
)。 然后,文件在重新启动时保持不变。