Search code examples
c++booststlofstreamostream

Using boost stream_buffer with std::ofstream


From the boost iostreams tutorial I have read that it is possible to use boost stream_buffer with std::ostream, as shown in the tutorial:

#include <ostream>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/stream.hpp>

namespace io = boost::iostreams;

int main()
{
    io::stream_buffer<io::file_sink> buf("log.txt");
    std::ostream                     out(&buf);
    // out writes to log.txt
}

How can we use boost stream_buffer to create std::ofstream? I have implemented a custom sink device that I can use to create a boost stream_buffer. With the stream buffer I am able to create std::ostream, but not std::ofstream.

// ...
io::stream_buffer<my_custom_file_sink> mybuf("myfile.txt"); // Creating stream_buffer works
std::ostream out(&mybuf); // Here I would like to use std::ofstream
// ...

I needed this because another library that I am using requires std::ofstream&. But unfortunately passing boost stream_buffer to std::ofstream constructor does not compile. Any possible workarounds?


Solution

  • What you can do is create an std::ofstream using its default constructor and then assign your buffer to it:

    io::stream_buffer<my_custom_file_sink> mybuf("myfile.txt");
    
    std::ofstream out;
    out.std::ostream::rdbuf(&mybuf); // Call the base class version.