如何重定向cout到控制台在linux? [英] How to redirect cout to console in linux?

查看:858
本文介绍了如何重定向cout到控制台在linux?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,它是另一个程序的一部分。在主程序中,它们将 cout 的默认方向重定向到LOG文件。为了调试我自己的程序,我需要重定向 cout 输出到控制台(终端)在linux。我不能像下面例子中描述的方法保存控制台 rdbuf

I am writing a program which is a part of another program. In the main program, they redirect the default direction of cout to a LOG file. For debugging of my own programm, I need to redirect the output of cout to console (terminal) in linux. I cannot save the console rdbuf like the method described in the example at:

http://www.cplusplus.com/reference/iostream/ios/rdbuf/

为了我的目的,是否有任何方法可以在c ++中获取linux的控制台?

Is there any way to get the handle to the console of linux in c++ for my purpose?

推荐答案

您需要定义控制台的含义,以及重定向的含义。如果你在一些上下文中运行程序,其输出被重定向到其他地方,并且你想重定向到控制终端(当他们说'控制台'时很多人的意思),你可以重定向到/ dev / tty,例如:

You need to define what you mean by the 'console' and what you mean by 'redirect'. If you're running a program in some context where its output has been redirected somewhere else, and you want to re-redirect it to the controlling terminal (what many people mean when they say 'console'), you can redirect to /dev/tty, eg:

program >/dev/tty

。以上可能是shell脚本中的一行,或者是一个作为参数传递给system(3)的字符串 - 这取决于你如何启动程序。

when you run the program. The above might be a line in a shell script, or be a string that is passed as an argument to system(3) -- it depends on how you're starting the program.

如果你想改变程序中的输出,你可以打开一个新的streambuf,指向你想要的,并使用ios :: rdbuf重定向到它:

If you want to change where the output is going within the program, you can open up a new streambuf referring to what you want, and use ios::rdbuf to redirect to it:

filebuf *console = new filebuf();
console->open("/dev/tty");
if (!console->is_open()) {
    cerr << "Can't open console" << endl;
} else {
    cout.ios::rdbuf(console);
}

这篇关于如何重定向cout到控制台在linux?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆