Search code examples
c++iostringstreamofstream

Substitute std::ofstream's underlying rdbuf with std::stringstream's underlying rdbuf


#include <fstream>
#include <ostream>
#include <sstream>

int main(int /*argc*/, char** /*argv*/)
{
    auto ofs = std::ofstream{"out.txt"};
    if (!ofs) { throw std::runtime_error{"ofstream"}; }
    
    auto ss = std::stringstream{};
    ss << "Hello world\n";

    static_cast<std::ostream&>(ofs).rdbuf(ss.rdbuf());
}

What I'm think is going to happen by the end of a program is ofs being RAII-closed and ss's buffer contents are to be written to out.txt. But out.txt is empty. What am I getting wrong ?


Solution

  • std::ofstream's default buffer is std::filebuf, which is what manages writing to the file. By replacing that buffer with a std::stringbuf, you are effectively turning your file stream into a string stream, where any writes to the std::ofstream will then go to a std::string in memory rather than to the file.

    If what you actually want to do is write the contents of the std::stringstream's buffer into the file, you can do this instead:

    ofs << ss.rdbuf();