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.
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.
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With