Redirecting function output to /dev/null

前端 未结 3 976
囚心锁ツ
囚心锁ツ 2020-12-09 17:02

I am using a library that is printing a warning message to cout or cerr. I don\'t want this warning message to reach the output of my program. How

3条回答
  •  星月不相逢
    2020-12-09 17:50

    Use ios::rdbuf:

    #include 
    
    void foo()
    {
        std::cout << "Boring message. " << std::endl;
    }
    
    int main()
    {
        ofstream file("/dev/null");
    
        //save cout stream buffer
        streambuf* strm_buffer = cout.rdbuf();
    
        // redirect cout to /dev/null
        cout.rdbuf(file.rdbuf());
    
        foo();
    
        // restore cout stream buffer
        cout.rdbuf (strm_buffer);
    
        std::cout << "Interesting message." << std::endl;
        return 0;
    }
    

提交回复
热议问题