如何在Linux中将cout重定向到控制台?

发布于 2024-12-24 19:02:20 字数 330 浏览 3 评论 0原文

我正在编写一个程序,它是另一个程序的一部分。在主程序中,它们将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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你列表最软的妹 2024-12-31 19:02:20

我无法编译克里斯的例子。
我发现“控制台->打开”中没有声明“->打开”。
我正在使用 kdevelop 4.5.2 来编译它,有效的是这段代码

ofstream console("/dev/tty"); //create stream
cout.rdbuf(console.rdbuf()); //redirects cout to the new stream

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

ofstream console("/dev/tty"); //create stream
cout.rdbuf(console.rdbuf()); //redirects cout to the new stream
新一帅帅 2024-12-31 19:02:20

您需要定义“控制台”和“重定向”的含义。如果您在某个上下文中运行一个程序,其输出已重定向到其他地方,并且您想将其重新重定向到控制终端(许多人说“控制台”时的意思),您可以重定向到 /dev /tty,例如:

program >/dev/tty

运行程序时。上面的内容可能是 shell 脚本中的一行,或者是作为参数传递给 system(3) 的字符串——这取决于您启动程序的方式。

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

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

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

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:

filebuf *console = new filebuf();
console->open("/dev/tty");
if (!console->is_open()) {
    cerr << "Can't open console" << endl;
} else {
    cout.ios::rdbuf(console);
}
冬天旳寂寞 2024-12-31 19:02:20

cout 转到 stdout,根据定义,它是文件描述符 1。

cout goes to stdout, which is file descriptor 1, by definition.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文