4

I am using a std::ofstream for trace output.

For some reasons, I sometimes want to dupplicate what I have appended at the end of the std::ofstream (that is not flushed or closed yet), into another std::ofstream;

Do you think of any way of achieving this ?

Thx

Stephane Rolland
  • 38,876
  • 35
  • 121
  • 169
  • 1
    For the moment I am reconsidering my problem. I use temporary std::stringstream, which I append to ofstream or dupplicate them according to the needs. It can do the job. – Stephane Rolland Apr 21 '11 at 13:25
  • yep, I thought about this. I was just going to write it (: But I wonder if there's a better way and give up answering :D +1 – Kiril Kirov Apr 21 '11 at 13:26
  • I tried, but rdbuf is not settable for ofstream; I wasn't so sure it would work anyway – sehe Apr 21 '11 at 13:35

1 Answers1

7

The Tee filter from Boost.Iostreams can split an output stream into two.

Here's an example inspired heavily by the one given by Johannes Schaub in his answer here.

#include <sstream>
#include <iostream>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/tee.hpp>

int main()
{
    namespace io = boost::iostreams;
    typedef io::tee_device<std::ostream, std::stringstream> TeeDevice;
    typedef io::stream<TeeDevice> TeeStream;
    std::stringstream ss;
    TeeDevice teeDevice(std::cout, ss);
    TeeStream tee(teeDevice);
    tee << "Hello World\n" << std::flush;
    std::cout << "ss: " << ss.str() << "\n";
}

When I omit the flush manipulator, ss.str() returns an empty string. I don't know whether or not this is the expected behaviour.

Community
  • 1
  • 1
Emile Cormier
  • 28,391
  • 15
  • 94
  • 122
  • yes, the behavior of the stringstream is expected. `stringstream` is [buffered](http://www.cplusplus.com/reference/iostream/stringstream/) and the buffer is written after [`flush`](http://www.cplusplus.com/reference/iostream/ostream/flush/). `endl` flushes the stream, too. – Christian Apr 15 '12 at 14:26