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;
}
}
>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 |