首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何组合输出流,使输出一次转到多个地方?

如何组合输出流,使输出一次转到多个地方?
EN

Stack Overflow用户
提问于 2009-11-19 11:35:12
回答 2查看 10.9K关注 0票数 21

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

我在考虑做这样的事情:

代码语言:javascript
复制
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中的调用将类似于:

代码语言:javascript
复制
// anything that goes to cout goes to both cout and the file
stream_compose coutToFile(std::cout, theFile);
// and so on

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

有没有其他更好/更简单的方法来实现这一点?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2009-11-19 22:03:31

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

票数 12
EN

Stack Overflow用户

发布于 2009-11-19 13:13:46

我会编写一个自定义的流缓冲区,它只是将数据转发到所有链接的流的缓冲区。

代码语言:javascript
复制
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <functional>

class ComposeStream: public std::ostream
{
    struct ComposeBuffer: public std::streambuf
    {
        void addBuffer(std::streambuf* buf)
        {
            bufs.push_back(buf);
        }
        virtual int overflow(int c)
        {
            std::for_each(bufs.begin(),bufs.end(),std::bind2nd(std::mem_fun(&std::streambuf::sputc),c));
            return c;
        }

        private:
            std::vector<std::streambuf*>    bufs;

    };  
    ComposeBuffer myBuffer;
    public: 
        ComposeStream()
            :std::ostream(NULL)
        {
            std::ostream::rdbuf(&myBuffer);
        }   
        void linkStream(std::ostream& out)
        {
            out.flush();
            myBuffer.addBuffer(out.rdbuf());
        }
};
int main()
{
    ComposeStream   out;
    out.linkStream(std::cout);
    out << "To std::cout\n";

    out.linkStream(std::clog);
    out << "To: std::cout and std::clog\n";

    std::ofstream   file("Plop");
    out.linkStream(file);
    out << "To all three locations\n";
}
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1760726

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档