bph
bph

Reputation: 11278

freopen usage to redirect output back to stdout after directing to a file

I'm using freopen for a GUI application using my shared library such that I can redirect debug msgs from stdout to a file

I have been using code based on a snippet from the C++ reference site:

/* freopen example: redirecting stdout */
#include <stdio.h>

int main ()
{
  freopen ("myfile.txt","w",stdout);
  printf ("This sentence is redirected to a file.");
  fclose (stdout);
  return 0;
}

This redirects stdout to myfile.txt and finally closes stdout

Is there a way to redirect to a file then effectively remove the redirection such that stdout then prints to screen as usual rather than closing it with fclose?

Upvotes: 1

Views: 2059

Answers (3)

Vincent Berthiaume
Vincent Berthiaume

Reputation: 87

This will return stdout to the display (the default stdout):

freopen( "CON", "w", stdout );

taken from here: http://support.microsoft.com/kb/58667

Upvotes: 1

David Grayson
David Grayson

Reputation: 87541

I haven't done it before, but try using dup to make a new file descriptor that is a copy of stdout before freopen, then later use dup2 to copy the properties of that new descriptor back to stdout.

http://linux.die.net/man/2/dup2

This is assuming your system even has dup. Let me know if it works!

Upvotes: 2

Per Johansson
Per Johansson

Reputation: 6887

No, not in pure C. If you can assume a specific system (e.g. POSIX) there probably are options.

But frankly, freopen is IMO a hack, only needed to be compatible with prewritten code. If you're writing new code you should instead pass the FILE * to the relevant functions and use fprintf instead of printf.

Upvotes: 3

Related Questions