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

ked picture ked · Aug 3, 2011 · Viewed 52.1k times · Source

I have a 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: (C++)

 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.

Answer

Chad picture Chad · Aug 3, 2011

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;