Coutinued output in file at each run

80 views Asked by At

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 .

2

There are 2 answers

4
Andrew On BEST ANSWER

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.

0
Some programmer dude On

By default opening a file for writing overwrites the existing file, if there is any. You need to specify an open mode that leaves the file as is. For example ate or app (which one to pick depends on your use-case).

This std::ofstream::open reference might help too.