views:

210

answers:

2

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?

+1  A: 

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.

Arkaitz Jimenez
if you want to keep printing your own stuff to stdout you should `dup()` it first. Then you can switch back and forth with `dup2()` if you want.
roe
or write your own data directly to the duped fd... I suppose that would be even better. still need to dup it though.
roe
Assuming a POSIX system, of course, and even then you're doing potentially dangerous things where reopen() perfectly fits the bill. C library <stdio.h> and POSIX <fcntl.h> don't mix well. I would always keep open() / read() / write() / close() and fopen() / fread() / fwrite() / fclose() well apart.
DevSolar
@roe you are right with the dup, @DevSolar yes, asuming a POSIX system
Arkaitz Jimenez
+6  A: 

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

Ferruccio
+1 for doing the standard-compliant (and portable) thing.
DevSolar
is it somehow permament till the end of the program? do i need to somehow convert it back to put to console again?
paul simmons