C/C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs (just like water and oil flowing through a pipe). In input operations, data bytes flow from an input source (such as keyboard, file, network or another program) into the program.
Input Stream: If the direction of flow of bytes is from the device(for example, Keyboard) to the main memory then this process is called input. Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device( display screen ) then this process is called output.
An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.
I'd like to compose two (or more) streams into one. My goal is that any output directed to cout
, cerr
, and clog
also be outputted into a file, along with the original stream. (For when things are logged to the console, for example. After closing, I'd like to still be able to go back and view the output.)
I was thinking of doing something like this:
class stream_compose : public streambuf, private boost::noncopyable { public: // take two streams, save them in stream_holder, // this set their buffers to `this`. stream_compose; // implement the streambuf interface, routing to both // ... private: // saves the streambuf of an ios class, // upon destruction restores it, provides // accessor to saved stream class stream_holder; stream_holder mStreamA; stream_holder mStreamB; };
Which seems straight-forward enough. The call in main then would be something like:
// anything that goes to cout goes to both cout and the file stream_compose coutToFile(std::cout, theFile); // and so on
I also looked at boost::iostreams
, but didn't see anything related.
Are there any other better/simpler ways to accomplish this?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With