将函数输出重定向到/ dev / null

编程入门 行业动态 更新时间:2024-10-24 14:17:21
本文介绍了将函数输出重定向到/ 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

本文发布于:2023-07-06 07:33:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047328.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   重定向   null   dev

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!