redirect std::cout to a custom writer

前端 未结 5 1184
生来不讨喜
生来不讨喜 2020-12-08 18:14

I want to use this snippet from Mr-Edd\'s iostreams article to print std::clog somewhere.

#include 
#include 
#include 

        
5条回答
  •  时光说笑
    2020-12-08 18:30

    I encourage you to look at Boost.IOStreams. It seems to fit your use-case nicely, and using it is surprisingly simple:

    #include  
    #include 
    #include 
    
    namespace bio = boost::iostreams;
    
    class MySink : public bio::sink
    {
    public:
        std::streamsize write(const char* s, std::streamsize n)
        {
            //Do whatever you want with s
            //...
            return n;
        }
    };
    
    int main()
    {
        bio::stream_buffer sb;
        sb.open(MySink());
        std::streambuf * oldbuf = std::clog.rdbuf(&sb);
        std::clog << "hello, world" << std::endl;
        std::clog.rdbuf(oldbuf);
        return 0;
    }
    

提交回复
热议问题