16.11: Redirection (freopen)

For some programs, standard input and standard output are enough, and these programs can get by using just getchar, putchar, printf, etc., and letting any input/output redirection be handled by the user and the operating system (perhaps using command-line redirection such as < and >). Other programs handle all file manipulation themselves, opening files with fopen and maintaining file pointer (FILE *) variables recording the streams to which all input and output is done (with getc, putc, fprintf, etc.).

Occasionally, a program has to be rewritten in a hurry, to allow it to read or write a named file without manipulating file pointers and changing every call to getchar to getc, every call to printf to fprintf, etc. In these cases, the function freopen comes in handy: it reopens an existing stream on a new file. The prototype is

	FILE *freopen(char *filename, char *mode, FILE *fp)
freopen is about like fopen, except that rather than allocating a new stream, it uses (and returns) the caller-supplied stream fp. For example, to redirect a program's output to a file ``from within,'' you could call
	freopen(filename, "w", stdout);

A disadvantage of freopen is that there's generally no way to undo it; you can't change your mind later and make stdin or stdout go back to where they had been before you called freopen. In situations where you want to be able to swich back and forth between streams, it's much better if you can chase down and change every call to getchar to getc, every call to printf to fprintf, etc., and then use some FILE * variable under your control (typically with a name like ifp or ofp) so that you can set it to point to a file by calling fopen, and later back to stdin or stdout by simply reassigning it.

Read sequentially: prev next up top

This page by Steve Summit // Copyright 1996-1999 // mail feedback