Search code examples
c++boost-iostreams

C++ "hello world" Boost tee example program


The Boost C++ library has Function Template tee

The class templates tee_filter and tee_device provide two ways to split an output sequence so that all data is directed simultaneously to two different locations.

I am looking for a complete C++ example using Boost tee to output to standard out and to a file like "sample.txt".


Solution

  • Based on help from the question John linked:

    #include <boost/iostreams/tee.hpp>
    #include <boost/iostreams/stream.hpp>
    #include <fstream>
    #include <iostream>
    
    using std::ostream;
    using std::ofstream;
    using std::cout;
    
    namespace bio = boost::iostreams;
    using bio::tee_device;
    using bio::stream;
    
    int main()
    {
        typedef tee_device<ostream, ofstream> TeeDevice;
        typedef stream<TeeDevice> TeeStream;
        ofstream ofs("sample.txt");
        TeeDevice my_tee(cout, ofs); 
        TeeStream my_split(my_tee);
        my_split << "Hello, World!\n";
        my_split.flush();
        my_split.close();
    }