Redirecting function output to /dev/null

前端 未结 3 968
囚心锁ツ
囚心锁ツ 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:28

    May I suggest a hack? Set a bad/fail bit on the relevant stream before use of a library function.

    #include <iostream>
    
    void foo()
    {
        std::cout << "Boring message. " << std::endl;
    }
    
    int main()
    {
        std::cout.setstate(std::ios::failbit) ;
        foo();
        std::cout.clear() ;
        std::cout << "Interesting message." << std::endl;
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-09 17:49

    If you are sure that thing does not redirect output (e.g. to /dev/tty/, which would be standard-out again) (which I don't think), you could redirect before calling them.

    #include <iostream>
    #include <sstream>
    
    void foobar() { std::cout << "foobar!\nfrob!!"; }
    
    int main () {    
        using namespace std;
    
        streambuf *old = cout.rdbuf(); // <-- save        
        stringstream ss;
    
        cout.rdbuf (ss.rdbuf());       // <-- redirect
        foobar();                      // <-- call
        cout.rdbuf (old);              // <-- restore
    
        // test
        cout << "[[" << ss.str() << "]]" << endl;
    }
    
    0 讨论(0)
  • 2020-12-09 17:50

    Use ios::rdbuf:

    #include <iostream>
    
    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;
    }
    
    0 讨论(0)
提交回复
热议问题