Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Redirect Output

Tags:

c++

redirect

Is there a way to redirect c++ output inside the code? The situation is this, I am using some external .cpp and .h files which use printf's to put warnings to console. I wish to redirect "only" these outputs (not mine) to a file "without" modifying their code.

So; in my program, I can redirect ouput to a file, and when I will put some output redirect again to default console, after that again to file, so on...

Is it possible?

like image 745
paul simmons Avatar asked Nov 19 '09 14:11

paul simmons


2 Answers

You can use freopen() on stdout to redirect stdout to a file.

like image 145
Ferruccio Avatar answered Nov 06 '22 03:11

Ferruccio


printf will print to file descriptor 1, you can close it and open a file, this will give you another fd, possibly 1 because its the lowest fd available, if not you weren't fast enough.

If you just close(1); and then int fd = open(file); fd should be 1 if none has opened something between the close and the open. At that point anyone outputting to fd number 1 will print to your file.

This is because the system should give you the lowest available file descriptor number so it'll give you 1 which is exactly where printf writes.

As @roe mentioned you might prefer to do a dup() over 1 first to get another fd number where you can print to stdout.

like image 22
Arkaitz Jimenez Avatar answered Nov 06 '22 04:11

Arkaitz Jimenez