How to override cout in C++?

前端 未结 9 1420
礼貌的吻别
礼貌的吻别 2020-12-07 02:47

I have a requirement, I need to use printf and cout to display the data into console and file as well. For printf I have

9条回答
  •  时光取名叫无心
    2020-12-07 03:43

    You can swap the underlying buffers. Here is that done facilitated through RAII.

    #include 
    
    class buffer_restore
    {
        std::ostream&   os;
        std::streambuf* buf;
    public:
        buffer_restore(std::ostream& os) : os(os), buf(os.rdbuf())
        { }
    
        ~buffer_restore()
        {
            os.rdbuf(buf);
        }
    };
    
    int main()
    {
        buffer_restore b(std::cout);
        std::ofstream file("file.txt");
    
        std::cout.rdbuf(file.rdbuf());
        // ...
    }
    

提交回复
热议问题