Redirect Output in UNIX: How to Use freopen() to Print to Console

  • Thread starter Thread starter ptabor
  • Start date Start date
  • Tags Tags
    Unix
Join the discussion
Registration is free. Start your own thread to ask a follow-up.
1 reply · 5K views
ptabor
Messages
14
Reaction score
0
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?
 
Physics news on Phys.org
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.
 
Last edited: