Jude Pereira
Jude Pereira

Reputation: 83

How to redirect stdout back to the terminal window

I need to redirect some output that would normally be printed to screen into a file. I have been able to redirect output to the file but I can't seem to figure out how to direct the output of the rest of my program back to the terminal window.

All code is in C. The program is running on Ubuntu.

Any insight as to what needs to be done?

Upvotes: 3

Views: 2172

Answers (2)

Jonathan Leffler
Jonathan Leffler

Reputation: 753475

I'm assuming you start with standard output unredirected. You then close the original standard output and reopen it to send standard output to a file - possibly using freopen(). When you've finished writing to the file, you want to reconnect standard output to the terminal.

If that's correct, you probably need to use freopen() to open the /dev/tty file. Note that this is not wholly reliable; if the program is being run without a terminal (for example, if it is run from a cron job), opening /dev/tty will fail.

It would be better (as in simpler), though, to have the code that writes to a file take a file stream argument so that you do not have to rely on redirecting and re-redirecting standard output.

If you are working with file descriptors, you could use dup() on the standard output file descriptor before doing the initial redirection to file. You could then use dup() again to reconnect the original standard output back to the original file descriptor after closing the redirected standard output.

Upvotes: 5

Charlie Martin
Charlie Martin

Reputation: 112356

Well, you sound like you're describing a mix of output, some to screen and some to a file. If so, you will need to get another file descriptor and use that to write one or the other. A file descriptor can't point to more than one destination.

On the off chance you mean all the output to go to both screen and file, then have a look at the tee(1) command.

Upvotes: 1

Related Questions