Reputation: 52
I want to append text to the file "filename.txt" but the text won't append. I have even set the attribute ios_base::app but it does not work(I have tried deleting the file and starting the program again so that the part where the attribute is added will be run;
ifstream MyReadFile("filename.txt");
ifstream f("filename.txt");
bool exits_and_can_be_opened = f.good();
if (exits_and_can_be_opened) {
cout << "This file already exists";
}
else {
MyWriteFile.open("filename.txt", ios_base::app);
MyWriteFile << "Files can be tricky, but it is fun enough!";
MyWriteFile.close();
}
while (getline(MyReadFile, myText)) {
// Output the text from the file
cout << myText << "\n";
}
MyWriteFile << "This thing was appended";
cout << "This was the final change";
Upvotes: 0
Views: 44
Reputation: 87959
You could open the file for reading and writing, and then use positioning functions to move around in the file or to switch from reading to writing
fstream MyFile("filename.txt");
while (getline(MyFile, myText)) {
// Output the text from the file
cout << myText << "\n";
}
MyFile.clear(); // clear any error
MyFile.seekg(0, ios_base::end); // move to the end of the file
MyFile << "This thing was appended";
The other (maybe simpler) way is to close and reopen the file every time you want to switch from reading to writing. Don't have the same file opened twice simultaneously.
Upvotes: 1