home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c
- Path: sparky!uunet!newsgate.watson.ibm.com!yktnews!admin!curt
- From: curt@watson.ibm.com (Curt McDowell)
- Subject: Re: redirecting stdout
- Sender: news@watson.ibm.com (NNTP News Poster)
- Message-ID: <1992Jul25.232634.7251@watson.ibm.com>
- Date: Sat, 25 Jul 1992 23:26:34 GMT
- Lines: 61
- Disclaimer: This posting represents the poster's views, not necessarily those of IBM
- References: <1992Jul25.184724.27204@news.acns.nwu.edu>
- Nntp-Posting-Host: gorby.watson.ibm.com
- Organization: IBM T.J. Watson Research Center
- Keywords: stdout, redirect
-
- In article <1992Jul25.184724.27204@news.acns.nwu.edu>, tindall@casbah.acns.nwu.edu (Mike Tindall) writes:
- > How can I return stdout to printing to the screen after redirecting
- > it to a file using out_file=freopen("fname","w",stdout)?
-
- The following works for me. I think it's reasonably robust, but I've only
- tested it using the example main() program below.
-
- ----------------------------------------------------------------------------
-
- #include <stdio.h>
-
- /*
- * redirect_stdout by Curt McDowell, IBM 07-25-92
- *
- * Redirects stdout to a file in a fairly idiot-proof way. Returns 0
- * unless there is an error writing the specified file, in which case
- * it returns -1, sets errno, and leaves stdout alone. If filename is
- * NULL, stdout is restored to the real stdout.
- */
-
- int redirect_stdout(filename)
- char *filename;
- {
- static int ofd = -1;
-
- if (filename) {
- if (ofd < 0 && (ofd = dup(1)) < 0)
- return -1;
- if (freopen(filename, "w", stdout) == 0) {
- redirect_stdout(0);
- return -1;
- }
- } else if (ofd >= 0) {
- freopen("/dev/null", "w", stdout);
- dup2(ofd, 1); /* Sneak in under stdio */
- close(ofd);
- ofd = -1;
- setlinebuf(stdout);
- }
-
- return 0;
- }
-
- main()
- {
- printf("This goes to the screen\n");
-
- redirect_stdout("file1");
-
- printf("This goes to file1\n");
-
- redirect_stdout("file2");
-
- printf("This goes to file2\n");
-
- redirect_stdout(0);
-
- printf("This goes back to the screen\n");
- }
-
- ----------------------------------------------------------------------------
- Curt McDowell IBM and I disclaim anything that
- IBM T. J. Watson Research Center happens as a result of this post.
-