J
John Kelly
comp.lang.c FAQ 12.33 says:
Hmmm ...
Why not leave the stream unchanged, and manipulate its underlying file
descriptor:
a) fflush() the stdio stream
b) dup the stdio fd to an unused fd, saving a copy of it.
c) close the stdio fd
d) use open() to get an fd for the desired file, and compare the fd
number to STDIN_FILENO or STDOUT_FILENO, as appropriate, to be sure
it matches; if not, use dup2() to copy it to the stdio fd
e) when done, use dup2() to copy the saved fd back to the stdio fd
Q: How can I redirect stdin or stdout to a file from within a program?
A: Use freopen. If you're calling a function f() which writes to stdout,
and you want to send its output to a file, and you don't have the option
of rewriting f, you can use a sequence like:
freopen(file, "w", stdout);
f();
Hmmm ...
See, however, question 12.34.
Question 12.34
Q: Once I've used freopen, how can I get the original stdout (or stdin) back?
A: There isn't a good way. If you need to switch back, the best solution is not
to have used freopen in the first place.
Why not leave the stream unchanged, and manipulate its underlying file
descriptor:
a) fflush() the stdio stream
b) dup the stdio fd to an unused fd, saving a copy of it.
c) close the stdio fd
d) use open() to get an fd for the desired file, and compare the fd
number to STDIN_FILENO or STDOUT_FILENO, as appropriate, to be sure
it matches; if not, use dup2() to copy it to the stdio fd
e) when done, use dup2() to copy the saved fd back to the stdio fd