Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 can I catch this output and put it into /dev/null or similar?

MWE:

#include <iostream>

void foo()
{
    std::cout << "Boring message. " << std::endl;
};

int main()
{
    foo();
    std::cout << "Interesting message." << std::endl;
    return 0;
}

The output should be:

Interesting message.

How should I modify main to get the desired output? (foo must not be changed.)


I tried using freopen() and fclose(stdout) as suggested in this question How can I redirect stdout to some visible display in a Windows Application?. The result is that nothing is printed.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
246 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...