Path: utzoo!attcan!uunet!jarthur!usc!apple!oracle!news From: wkaufman@oracle.oracle.com (William P. Kaufman) Newsgroups: comp.lang.c Subject: Re: I/O redirection Message-ID: <1990Apr6.002332.8371@oracle.com> Date: 6 Apr 90 00:23:32 GMT References: <1990Apr2.144841.12905@mentor.com> Reply-To: wkaufman@oracle.com (William P. Kaufman) Organization: Oracle Corporation, Belmont CA Lines: 36 In article <1990Apr2.144841.12905@mentor.com> swhitchurch@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