PDA

View Full Version : freopen() in UNIX


ptabor
May15-07, 02:18 PM
So I'm using freopen to redirect output from stdout to a file... How do I redirect it back to the screen?

relevant code:

FILE *stream = freopen("data.txt", "w", stdout);

/* print stuff */




How the heck do I get the output stream to point to the console again?

AlephZero
May15-07, 03:28 PM
On Unix, you can access "the screen" (and every other device) via a filename. /dev/tty is a good bet for what stdout was attached to.

freopen("/dev/tty",...) should work.

But this isn't a very polite thing to do, because stdout might have been redirected by the user.

Another idea would be something like this:

FILE *myfile;
FILE *datafile = fopen("data.txt"...);

Then do

myfile = stdout;
or
myfile = datafile;

(filp back and forth as often as you like)

and do all your I/O to myfile.