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

  • Thread starter Thread starter ptabor
  • Start date Start date
  • Tags Tags
    Unix
AI Thread Summary
To redirect output from stdout to a file using freopen, the code snippet provided demonstrates how to write to "data.txt." To revert the output back to the console, using freopen("/dev/tty", "w", stdout) is suggested, as it directs output to the terminal. However, this method may not be ideal since it can disrupt user-defined redirections. An alternative approach involves using a separate file pointer, allowing for flexible switching between stdout and the file. By assigning stdout or the file to a custom pointer, users can control where their output is directed without interfering with the original stdout settings. This method enables seamless toggling between output streams.
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?
 
Technology 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:
Dear Peeps I have posted a few questions about programing on this sectio of the PF forum. I want to ask you veterans how you folks learn program in assembly and about computer architecture for the x86 family. In addition to finish learning C, I am also reading the book From bits to Gates to C and Beyond. In the book, it uses the mini LC3 assembly language. I also have books on assembly programming and computer architecture. The few famous ones i have are Computer Organization and...
I have a quick questions. I am going through a book on C programming on my own. Afterwards, I plan to go through something call data structures and algorithms on my own also in C. I also need to learn C++, Matlab and for personal interest Haskell. For the two topic of data structures and algorithms, I understand there are standard ones across all programming languages. After learning it through C, what would be the biggest issue when trying to implement the same data...
Back
Top