我想在带有std::fstream的文件中附加一些文本。我写了这样的东西

class foo() {
   foo() {}
   void print() {
      std::fstream fout ("/media/c/tables.txt", std::fstream::app| std::fstream::out);
      // some fout
   }
};


这种结构的问题是,每当我运行程序时,这些文本就会追加到我以前的运行中。例如,在第一次运行结束时,文件大小为60KB。在第二次运行的开始,这些文本将附加60KB文件。

要解决此问题,我想在构造函数中初始化fstream,然后在追加模式下将其打开。像这样

class foo() {
   std::fstream fout;
   foo() {
      fout.open("/media/c/tables.txt", std::fstream::out);
   }
   void print() {
      fout.open("/media/c/tables.txt", std::fstream::app);
      // some fout
   }
};


该代码的问题是在执行期间和运行结束时大小为0的文件!

最佳答案

您只需要打开一次文件:

class foo() {
    std::fstream fout;
    foo() {
        fout.open("/media/c/tables.txt", std::fstream::out);
    }
    void print() {
      //write whatever you want to the file
    }
    ~foo(){
        fout.close()
    }
};

关于c++ - 启动时清除文件内容,然后追加,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14940027/

10-15 06:41