2

I have created a code writing stuff in a .txt file and read from it. But if I close the program and start to write again, it deletes the old text and overwrites it with the new one.

Is there a way to not overwrite existed data?

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

void check() {

    string text;
    ifstream file;
    file.open("test.txt");
    getline(file, text);

    if (text == "") {
        cout << "There's no data in file" << endl;
    } else {
        cout << "File contains:" << endl;
        cout << text << endl;
    }
}

int main() {

    check();

    string text;
    ofstream file;
    file.open("test.txt");
    cout << "Type some text" << endl;
    getline(cin, text);
    file << text;

    return 0;
}
diziaq
  • 6,881
  • 16
  • 54
  • 96
David Rojko
  • 27
  • 1
  • 1
  • 4

4 Answers4

9

You need to open the file in 'append' mode like in the following example

#include <fstream>

int main() {  
  std::ofstream outfile;

  outfile.open("yourfile.txt", std::ios_base::app);//std::ios_base::app
  outfile << "your data"; 
  return 0;
}

You can read here about fstream flags
http://www.cplusplus.com/reference/fstream/fstream/open/

Evyatar Elmaliah
  • 634
  • 1
  • 8
  • 23
1

Keep in mind that in c++ there are several ways to open, save, and read text data to and from a file. It sounds like you opened with with a function (and its options) to always create a new file. One thing you could do is run your program and then close the program and use a text editor to open the file to verify whether the text you wrote to the file is actually there. Also take a look at the code that was provided by Evyatar. That example uses ofstream which allows options for read, write, and append. The "app" parameter tells the program to keep what is already in the file and append any new data that you add in the next run. When testing files where you are appending, be careful you don't end up with a huge file you did not intend to have so large.

K17
  • 697
  • 3
  • 8
  • 26
1

In the code that you posted in your revised question, be sure to close the file in your check function and at the end of the program. It is possible to get things hung up if you don't. As a precaution, I usually close a file prior to opening it, just to be sure it is closed with no problems. This practice comes form my days programming in BASIC where it was an essential. If the program crashed, you couldn't open it again until you got it closed. Also, of course, close the file after you're done with it and before the end of the program. Then, when you open it in main, open with the append option.

K17
  • 697
  • 3
  • 8
  • 26
0

Please, insert code for next time. If you open file in write mode, than is normal that every time you write to file, the content of file is changed. You need to use append mode.

Jaro Kollár
  • 253
  • 3
  • 15