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?
You can use freopen() on stdout to redirect stdout to a file.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With