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?
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/ttyfile. 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/ttywill 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 usedup()again to reconnect the original standard output back to the original file descriptor after closing the redirected standard output.