C++ 重新启动后,使用ofstream创建的文件为空
我正在使用流的C++ 重新启动后,使用ofstream创建的文件为空,c++,c++11,C++,C++11,我正在使用流的实现一个函数来更新/etc/dns.conf中的配置文件。但我的文件在系统重新启动后是空的(文件在那个里但并没有内容) 我原以为flush()会立即将内容同步到物理文件中,但我的实现出了问题。请帮我找到真正的问题 基本上,我使用所需的数据创建了一个tmp文件/etc/dns.bak,然后删除原始文件/etc/dns.conf,并将tmp文件重命名为/etc/dns.conf(注意,程序是以root用户身份运行的,所以所有文件权限都在那里) 以下步骤: 将所需数据添加到向量 使用扩
实现一个函数来更新/etc/dns.conf
中的配置文件。但我的文件在系统重新启动后是空的(文件在那个里但并没有内容)
我原以为flush()会立即将内容同步到物理文件中,但我的实现出了问题。请帮我找到真正的问题
基本上,我使用所需的数据创建了一个tmp文件/etc/dns.bak
,然后删除原始文件/etc/dns.conf
,并将tmp文件重命名为/etc/dns.conf
(注意,程序是以root用户身份运行的,所以所有文件权限都在那里)
以下步骤:
- 将所需数据添加到向量
- 使用扩展名为.bak的流的
打开tmp文件
- 迭代vector并使用
将数据写入文件我从未听说过名为dns.conf
的文件,但另一个名为resolv.conf
的文件也处理名称解析,在Linux系统重新启动时会自动覆盖。这里可能是这样吗?这是我的项目中使用的自定义配置文件。它可以是任何名称。@SajithP否。这些评论具有误导性。如果您关闭文件,那么您端上的任何缓冲区都将自动刷新到内核/硬件区。如果随后使用reboot
命令重新启动,则剩余的任何内容都将得到正确的同步、写入和处理。这些都不是你的问题。您的程序的所有内容都是正确的。其他内容正在覆盖您的文件。请尝试以下操作以缩小范围:1。将文件更改为~/dns.conf
和~/dns.bak
,运行测试,重新启动,检查文件内容。2.使用文本编辑器手动编辑/etc/dns.conf
,重新启动,检查其内容。3.在/etc中使用另一个文件,如/etc/test.conf
和/etc/test.bak
。运行你的程序。重新启动。4.运行程序后,检查/etc/dns.conf
上的时间戳。重新启动。再次检查文件时间戳。看看他们是否不同。请报告这四个结果。@JasonC我发现在重新启动之前调用sync()可以解决问题。我正在运行的CentOS版本没有网络管理器,因此在引导过程中不会对/etc中的dns配置进行更改。
#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;
}