Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!tut.cis.ohio-state.edu!att!cbnewsc!levy From: levy@cbnewsc.ATT.COM (Daniel R. Levy) Newsgroups: comp.lang.c Subject: Re: I/O redirection Summary: a few nit picks Message-ID: <15008@cbnewsc.ATT.COM> Date: 10 Apr 90 23:09:16 GMT References: <1990Apr2.144841.12905@mentor.com> <1418@quando.UUCP> Organization: AT&T Bell Laboratories, Skokie IL Lines: 75 In article <1418@quando.UUCP>, cmueller@quando.UUCP (Christoph Mueller) writes: < In article <1990Apr2.144841.12905@mentor.com> swhitchurch@mentor.com (Steve Whitchurch) writes: < >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 (); < #include < static int filedescr; < int redirect_stdout (filename) < char *filename; < { < filedescr = dup (1); < if (freopen (filename, "w", stdout) == (FILE *) 0) < { < return (-1); /* redirection failed */ < } < else < { < return (0); /* OK! */ < } < } < void reset_stdout () < { /* < fclose (stdout); ^^^^^^^^^^^^^^^^ It is unsafe to use stdout after fclose()'ing it. Better to */ fflush(stdout); close(1); /* You may want to be sure fd 0 is open first. Maybe the program closed it somewhere along the line; you're OK if it was closed when the program started, because "filedescr" will be fd 0 in that event. Otherwise, the dup() will return fd 0, and stdio writes to "stdout" will go to a still-closed fd 1. */ { #include /* O.K., this should be at the top of the file, but */ #include /* it is more self-explanatory here */ struct stat s; int fd0_open; if (!(fd0_open=(fstat(0,&s)==0))) open("/dev/null",0); < dup (filedescr); if (fd0_open) close(0); } < } < main () < { < char file [80]; < strcpy (file, "/tmp/out"); /* < redirect (file); Presumably redirect_stdout() was intended */ redirect_stdout(file); < printf ("This will be written into a file.\n"); < reset_stdout (); < printf ("This will be written to stdout.\n"); < } -- Daniel R. Levy >>> God: just say "yes" <<< AT&T Bell Laboratories UNIX(R) mail: att!ttbcad!levy, att!cbnewsc!levy 5555 West Touhy Avenue Any opinions expressed in the message above are Skokie, Illinois 60077 mine, and not necessarily AT&T's.