Search code examples
c++stringfilestreaming

Writing a string to the end of a file (C++)


I have a C++ program already formed that has a string that I want to stream to the end of an existing text file. All of what little I have is this:

void main()
{
    std::string str = "I am here";
    fileOUT << str;
}

I realize there is much to be added to this and I do apologize if it seems I am asking people to code for me, but I am completely lost because I have never done this type of programming before.

I have attempted different methods that I have come across the internet, but this is the closest thing that works and is somewhat familiar.


Solution

  • Open your file using std::ios::app

     #include <fstream>
    
     std::ofstream out;
    
     // std::ios::app is the open mode "append" meaning
     // new data will be written to the end of the file.
     out.open("myfile.txt", std::ios::app);
    
     std::string str = "I am here.";
     out << str;