Search code examples
c++file-handling

Opening an existing text file erases its contents altogether


I am trying to open a text file (it has content). Every time I open it, the content of the file ends up being erased altogether, which I do not want.

#include <fstream>
#include <iostream>

using namespace std;

int main() {
    string filename;
    cout << "Enter File name : ";
    cin >> filename;
    fstream file;
    file.open(filename, fstream::out);
    file.close();
    return 0;
}

Solution

  • Instead of fstream::out which discards everything which was previously present in the file, you should use fstream::app which will not delete the contents of the file and continue writing to it from its end.


    From cppreference:

    Constant Explanation
    app seek to the end of stream before each write
    binary open in binary mode
    in open for reading
    out open for writing
    trunc discard the contents of the stream when opening
    ate seek to the end of stream immediately after open
    noreplace (C++23) open in exclusive mode