重启后使用ofstream创建的文件为空

时间:2016-12-16 07:42:35

标签: c++ c++11

我正在使用ofstream实现一个函数来更新/etc/dns.conf中的配置文件。但是在系统REBOOT之后我的文件是EMPTY(文件在那里但没有内容)。

我认为flush()会立即将内容同步到物理文件。但是我的实现出了点问题。请帮我在这里找到真正的问题。

基本上我用所需数据创建一个tmp文件/etc/dns.bak,然后删除原始文件/etc/dns.conf并将tmp文件重命名为/etc/dns.conf(注意程序是以root身份运行所以所有文件权限在那里。)

遵循的步骤:

  • 将所需数据添加到矢量
  • 使用扩展名为.bak的ofstream打开tmp文件
  • 使用<<运算符
  • 迭代向量并将数据写入文件
  • 使用flush()
  • 刷新文件
  • 使用close()
  • 关闭文件
  • 使用std::remove
  • 删除原始文件
  • 使用std::rename
  • 将tmp文件重命名为原始文件
  • cat the file(它输出正确的内容/我也可以看到物理磁盘上的文件大小正确)
  • 15秒后重启系统
  • 发现
  • /etc/dns.conf为空(重启后没有任何内容)

由于我的代码库有更多的逻辑,我创建了一个与我正在使用的文件完全相同的代码段

#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)。   然后,文件在重新启动时保持不变。

0 个答案:

没有答案