Search code examples
c++filestlstdstringofstream

Copy the contents of std::ofstream into an std::string


I have an std::ofstream object that hasn't been flushed yet. Is there a way to get the contents of this ofstream and store it into a std::string?

What I want essentially is:

std::ofstream ofs("somefile.txt");
ofs << "stuff";
someMethod(ofs); //This method streams into ofs as well
ofs <<"blah";
yetAnotherMethod(ofs); //ofs gets violated inside this method as well 
//more data streamed into ofs
std::string s; //Whatever was streamed into ofs should go into s as well for an additional output.

Solution

  • No. "the contents of this std::ofstream" is nonsensical. The file has contents, the stream is a handle that represents writing to the file.

    Either flush ofs and read the file, or use std::ostream & in place of std::ofstream &.