I just read about freopen last night.
From man freopen
I think this might be what you want.
FILE *freopen(const char *filename, const char *mode, FILE
The freopen() function first attempts to flush the stream
and close any file descriptor associated with stream.
Failure to flush or close the file successfully is ignored.
The error and end-of-file indicators for the stream are
The freopen() function opens the file whose pathname is the
string pointed to by filename and associates the stream
pointed to by stream with it. The mode argument is used just
as in fopen(3C).
The freopen() function is typically used to attach the preo-
pened streams associated with stdin, stdout and stderr to
other files. By default stderr is unbuffered, but the use of
freopen() will cause it to become buffered or line-buffered.
Hope it works,