将函数输出重定向到/ dev / null [英] Redirecting function output to /dev/null
问题描述
我正在使用正在向 cout
或 cerr
打印警告消息的库。我不想让这个警告消息到达我的程序的输出。如何捕获此输出并将其放入 / dev / null
或类似的?
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;
}
输出应为:
Interesting message.
如何修改 main
以获得所需的输出? ( foo
不得更改。)
How should I modify main
to get the desired output? (foo
must not be changed.)
freopen()和 fclose(stdout)
如何在Windows应用程序中将stdout重定向到某个可见的显示? >。结果是什么也不打印。
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.
推荐答案
如果你确定这个东西不会重定向输出(例如到 / dev / tty / / code>,这将是标准输出再次)(我不认为),你可以重定向之前调用他们。
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;
}
这篇关于将函数输出重定向到/ dev / null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!