如何在Linux中将cout重定向到控制台?
我正在编写一个程序,它是另一个程序的一部分。在主程序中,它们将cout的默认方向重定向到LOG文件。为了调试我自己的程序,我需要将cout的输出重定向到Linux中的控制台(终端)。我无法像以下示例中描述的方法那样保存控制台 rdbuf:
http://www.cplusplus.com/reference/iostream/ios/rdbuf/
有没有办法为我的目的获取c++中linux控制台的句柄?
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/
Is there any way to get the handle to the console of linux in c++ for my purpose?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我无法编译克里斯的例子。
我发现“控制台->打开”中没有声明“->打开”。
我正在使用 kdevelop 4.5.2 来编译它,有效的是这段代码
I wasn't able to compile Chris example.
I got that "->open" was not declared in "console->open".
I'm using kdevelop 4.5.2 to compile it and what worked is the piece of code
您需要定义“控制台”和“重定向”的含义。如果您在某个上下文中运行一个程序,其输出已重定向到其他地方,并且您想将其重新重定向到控制终端(许多人说“控制台”时的意思),您可以重定向到 /dev /tty,例如:
运行程序时。上面的内容可能是 shell 脚本中的一行,或者是作为参数传递给 system(3) 的字符串——这取决于您启动程序的方式。
如果你想改变程序中输出的位置,你可以打开一个新的streambuf来引用你想要的内容,并使用 ios::rdbuf 重定向到它:
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:
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.
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:
cout
转到stdout
,根据定义,它是文件描述符 1。cout
goes tostdout
, which is file descriptor 1, by definition.