Search code examples
c++filestream

Coutinued output in file at each run


How to avoid updating the file content at each run

#include <iostream>
#include <fstream>
#include <math>

using namespace std;

int main() {
  ofstream file("file.txt");
  v2 = rand() % 100 + 1;
  file<< v2;
  file.close();
  return 0 ;
}

I am looking to add a new line at each run containing the new random value and conserving the old one wrote during the previous run .


Solution

  • You need to specify the "append" mode when opening the file:

    #include <iostream>
    #include <fstream>
    #include <math>
    
    int main() {
      std::ofstream file("file.txt", std::ios_base::app);
      v2 = rand() % 100 + 1;
      file << v2;
      file.close();
      return 0 ;
    }
    

    See http://en.cppreference.com/w/cpp/io/basic_ofstream/basic_ofstream and http://en.cppreference.com/w/cpp/io/ios_base/openmode for details. Opening a file for output, without specifying the open mode, will by default truncate the file.