Boost logo

Boost :

From: Jonathan Turkanis (technews_at_[hidden])
Date: 2005-02-27 15:19:37


Brian Braatz wrote:
> However, I am NOT (yet) an expert in the Iostreams library so please
> excuse me if I am missing something obvious.
>
>
> I add 2 sinks
>
> filtering_ostream out;
> out.push(file_sink("Report.txt"));
> out.push(cout);
>
> I get an exception thrown on the second one (regardless of which one
> goes in first)

This is true. A chain can only contain one device.

>
> In searching the archives, I noticed this mail:

<snip description of 'tee' filter>

I apparently didn't test that code, because it contained two errors (write takes
a const char* instead of a char*, and only multi-character filters implement
write() instead of put()). At the end of this message is an updated and tested
version.

I plan to include a tee filter in the first released version of the library. It
should be slightly more efficient than the example.

Jonathan

--------------

#include <boost/iostreams/concepts.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <fstream>
#include <iostream>

struct tee : boost::iostreams::multichar_output_filter {
    tee(std::ostream& dest) : dest(dest) { }

    template<typename Sink>
    void write(Sink& snk, const char* s, std::streamsize n)
    {
        // Write to the downstream Sink
        boost::iostreams::write(snk, s, n);

        // Write to the stored ostream:
        dest.write(s, n);
    }

    std::ostream& dest;
};

int main()
{
    using namespace boost::iostreams;
    std::ofstream log("C:/log.txt");
    filtering_ostream out;
    out.push(tee(log));
    out.push(std::cout);
    out << "this gets written to both ostreams\n";
}


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk