How to redirect cout to console in linux?

时光总嘲笑我的痴心妄想 提交于 2019-12-02 08:18:10

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

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

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

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