[英]How to temporarily suppress output from printf?
In a console application I am calling a library function that outputs some messages (probably using printf) that I am not interested in: 在控制台应用程序中,我调用一个库函数,输出一些我不感兴趣的消息(可能使用printf):
void libFoo()
{
// does some stuff
printf("boring message");
// does some more stuff
}
I tried suppressing cout before which didn't work, hence why I think libFoo is using printf: 我尝试压制cout之前没有用,因此我认为libFoo使用printf:
cout << "interesting messsage" << endl;
streambuf* orig_buf = cout.rdbuf();
cout.rdbuf(NULL);
libFoo();
cout.rdbuf(orig_buf);
cout << "another interesting messsage" << endl;
This code outputs all these messages. 此代码输出所有这些消息。 Is there a way to temporarily suppress output from printf?
有没有办法暂时抑制printf的输出? I am using Linux Mint.
我正在使用Linux Mint。
Here it is: 这里是:
int supress_stdout() {
fflush(stdout);
int ret = dup(1);
int nullfd = open("/dev/null", O_WRONLY);
// check nullfd for error omitted
dup2(nullfd, 1);
close(nullfd);
return ret;
}
void resume_stdout(int fd) {
fflush(stdout);
dup2(fd, 1);
close(fd);
}
If this is C++, also flush cout
for good measure. 如果这是C ++,也可以刷新
cout
以获得良好的衡量标准。
EDITED TO CLARIFY 编辑澄清
The fd
you pass to resume_stdout
is the same one you received as supress_stdout
's return value. 传递给
resume_stdout
的fd
与supress_stdout
的返回值相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.