如何组合输出流,以便输出一次到达多个位置?

2021-12-24 00:00:00 stream iostream c++ boost tee

我想将两个(或更多)流合二为一.我的目标是将指向 coutcerrclog 的任何输出与原始流一起输出到文件中.(例如,当事情被记录到控制台时.关闭后,我希望仍然能够返回并查看输出.)

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;
};

这似乎很直接.然后 main 中的调用将类似于:

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

我还查看了 boost::iostreams,但没有看到任何相关内容.

I also looked at boost::iostreams, but didn't see anything related.

还有其他更好/更简单的方法来实现这一目标吗?

Are there any other better/simpler ways to accomplish this?

推荐答案

你提到在 Boost.IOStreams 中没有找到任何东西.您是否考虑过 tee_device?

You mention having not found anything in Boost.IOStreams. Did you consider tee_device?

相关文章