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

  • Thread starter Thread starter ptabor
  • Start date Start date
  • Tags Tags
    Unix
Click For Summary
SUMMARY

The discussion focuses on using the C standard library function freopen() to redirect output from stdout to a file and then back to the console in a UNIX environment. The recommended approach to redirect output back to the console is to use freopen("/dev/tty", "w", stdout), which effectively points stdout back to the terminal. However, caution is advised as this method may disrupt user-defined redirections. An alternative method involves using a temporary file pointer to switch between stdout and a file, allowing for more controlled output management.

PREREQUISITES
  • Understanding of C programming language
  • Familiarity with standard I/O functions in C
  • Basic knowledge of UNIX file system and device files
  • Experience with file handling in C
NEXT STEPS
  • Research the freopen() function in the C standard library
  • Learn about device files in UNIX, specifically /dev/tty
  • Explore advanced file handling techniques in C, including using multiple file pointers
  • Investigate best practices for managing output streams in C applications
USEFUL FOR

C developers, UNIX system programmers, and anyone looking to manage output streams effectively in C applications.

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:

Similar threads

Replies
1
Views
4K
  • · Replies 11 ·
Replies
11
Views
2K
Replies
3
Views
3K
Replies
1
Views
7K
  • · Replies 3 ·
Replies
3
Views
2K
  • · Replies 1 ·
Replies
1
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 2 ·
Replies
2
Views
4K
  • · Replies 5 ·
Replies
5
Views
3K