简体   繁体   English

启动时清除文件内容,然后追加

[英]Clearing the content of file at startup and then append

I want to append some text in a file with std::fstream . 我想在带有std::fstream的文件中附加一些文本。 I wrote something like this 我写了这样的东西

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

Problem with this structure is that every time I run my program, the texts are appended to my previous run. 这种结构的问题是,每当我运行程序时,这些文本就会追加到我以前的运行中。 For example at the end of the first run the size of the file is 60KB. 例如,在第一次运行结束时,文件大小为60KB。 At the beginning of the second run, the texts are appended 60KB file. 在第二次运行的开始,这些文本将附加60KB文件。

To fix that I want to initialize the fstream in the constructor and then open it in append mode. 要解决此问题,我想在构造函数中初始化fstream,然后在追加模式下将其打开。 Like this 像这样

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
   }
};

Problem with this code is a 0 size file at during the execution and at the end of run!! 该代码的问题是在执行期间和运行结束时大小为0的文件!

you only need to open the file once : 您只需要打开一次文件:

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()
    }
};

Your class should look more like this: 您的班级应该看起来像这样:

#include <fstream>

class Writer
{
public:
    Writer(const char* filename) { of_.open(filename); }
    ~Writer(){ of_.close(); }
    void print() {
        // writing... of_ << "something"; etc.
        of_.flush();
    }
private:
    std::ofstream of_;
};

Note that file stream is being open only once at the moment the Writer object is being constructed and in the destructor close() is called, which also automatically writes any pending output to the physical file. 请注意,在构造Writer对象并在析构函数中调用close()的那一刻,文件流仅被打开一次,这还将自动将任何未决的输出写入物理文件。 Optionally after each time something is written to the stream, you can call flush() to make sure the output goes to your file ASAP. (可选)每次将某些内容写入流之后,您可以调用flush()来确保输出尽快到达您的文件。

Possible usage of this class: 该类的可能用法:

{
    Writer w("/media/c/tables.txt");
    w.print();
} // w goes out of scope here, output stream is closed automatically

ofstream out; 流出 // output file object //输出文件对象

out.open (fname1,ios::out); out.open(fname1,ios :: out); // open file // 打开文件

    **out.clear();** // clear previous contents

///////////// code to write file /////////////编写文件的代码

Eg out<<"hello"; 例如out <<“ hello”;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM