Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting function output to /dev/null

Tags:

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.

like image 813
Unapiedra Avatar asked Nov 23 '11 17:11

Unapiedra


People also ask

How do I redirect only stderr to Dev null?

Similarly, to redirect only the STDERR to /dev/null, use the integer '2' instead of '1' . The integer '2' stands for standard error. As you can see, the standard error is not displayed on the terminal now as it is discarded in /dev/null.

What is meant by Dev null 2 >& 1?

So in a sentence “1>/dev/null 2>&1” after a command means, that every Standard Error will be forwarded to the Standard Output and this will be also forwarded to a black hole where all information is lost.

What does piping to Dev null do?

In technical terms, “/dev/null” is a virtual device file. As far as programs are concerned, these are treated just like real files. Utilities can request data from this kind of source, and the operating system feeds them data. But, instead of reading from disk, the operating system generates this data dynamically.

How do I redirect standard output to a file?

Redirecting stdout and stderr to a file: The I/O streams can be redirected by putting the n> operator in use, where n is the file descriptor number. For redirecting stdout, we use “1>” and for stderr, “2>” is added as an operator.


1 Answers

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;
}
like image 149
wreckgar23 Avatar answered Sep 30 '22 02:09

wreckgar23