How to redirect cout to console in linux?

匆匆过客 提交于 2019-12-02 17:07:13

问题


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?


回答1:


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);
}



回答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

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



回答3:


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



来源:https://stackoverflow.com/questions/8690388/how-to-redirect-cout-to-console-in-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!