How to redirect cout to console in linux?

2019-03-04 17:35发布

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?

3条回答
Melony?
2楼-- · 2019-03-04 18:13

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);
}
查看更多
干净又极端
3楼-- · 2019-03-04 18:15

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

查看更多
Summer. ? 凉城
4楼-- · 2019-03-04 18:35

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
查看更多
登录 后发表回答