how to redirect back to stdout

In my program, I am using library provided by other. In the library, the cout/cerr is redirected to a file (the file path is known).

After I call some methods in the library, I get one side-effect --> The cout/cerr in my own program is also directed to the file.

So how can I to redirect cout/cerr BACK to standand output again? (BTW, my OS is Linux, and the programing language is C++)

You need to make a copy of stderr with dup() before the redirection happens, then copy it overtop of your own stderr after the redirection with dup2().

thanks for your answer, Corona688. yes, this is a way.

are the any other ways if I am not convenient (i.e. have no chance) to make a copy of stderr with dup() before the redirection happens?

Doing this in C++ is the same as doing this in C since the system calls are all the same.

stdin is probably the same terminal, but since it's opened with the wrong file mode duplicating it won't work right. But you might be able to figure out what the terminal at least is:

$ ls -l /dev/fd/0
lrwx------ 1 monttyle monttyle 64 Feb 17 09:15 /dev/fd/0 -> /dev/pts/1
$

If you don't have that, try /dev/stdin or /proc/self/fd/0

You can retrieve the same info in your C/C++ program with the readlink() call, then open the terminal and re-duplicate it over stdout and stderr.

This, of course, won't work when stdin was never a terminal, so be careful to not let your program do crazy things when you pipe or redirect into it.

You can first call isatty() on each file descriptor: 0, 1 to see if it is a terminal or not.

thanks a lot, guys.