Search code examples
c++appendfstream

Clearing the content of file at startup and then append


I want to append some text in a file with 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. At the beginning of the second run, the texts are appended 60KB file.

To fix that I want to initialize the fstream in the constructor and then open it in append mode. 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!!


Solution

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