Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Opening an existing text file erases its contents altogether

I am trying to open a text file in C++ (it has content). Every time I open, it ends up erasing the contents of the file 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;
}

}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading