Home > Back-end >  Text can not be appended to the file
Text can not be appended to the file

Time:08-04

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

CodePudding user response:

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.

  •  Tags:  
  • c
  • Related