I/O redirection
William P. Kaufman
wkaufman at oracle.oracle.com
Fri Apr 6 10:23:32 AEST 1990
In article <1990Apr2.144841.12905 at mentor.com> swhitchurch at mentor.com (Steve Whitchurch) writes:
>Hi;
>
>I have a question: I need to change or redirect "stdout" from inside
>a C function. What I want to do is capture the output of a printf and
>put the results into a file. so it would go something like this:
>
> redirect_stdout ();
> call_function_that_prints_to_stdout ();
> reset_stdout ();
>
Oooo, ugly. There is a way, but it's thouroughly machine-depedent. What you
can do is:
freopen(file, "w", stdout);
function..();
freopen("/dev/ttyXX", "w", stdout);
for a UNIX machine, assuming you know what terminal you're on,...or,...
Much easier is:
FILE *out_fp = stdout;
out_fp = fopen(new_file, "w");
call_function_that_prints_to_out_fp();
out_fp = stdout;
and change all your code from
printf(...);
ro
fprintf(out_fp, ...);
and put in some error checking. _That's_ portable (modulo file-naming
conventions), you don't need to know your terminal, etc., etc. Granted, it
won't work on procedures you can't control (say, perror()), but I hope it's
good enough for you.
Happy hunting,....
-- Bill Kaufman
More information about the Comp.lang.c
mailing list