freopen, fclose and stdout

A

Alex Vinokur

Hi,


freopen closes stdout, but it seems that fclose doesn't restore it (see sample below).

How can one print to stdout after using freopen?


========= C code : File foo.c : BEGIN =========
#include <stdio.h>
#include <assert.h>

#define FILE_NAME "foobar"

int main ()
{
FILE* out_fp;
int rc;

remove (FILE_NAME);

printf ( "printf-1\n");

out_fp = freopen (FILE_NAME, "a", stdout);
assert (out_fp);

printf ("printf-2\n");
fprintf (out_fp, "fprintf(out_fp)\n");

rc = fclose (out_fp);
assert (!rc);

printf ("printf-3\n"); // Problematic printf

return 0;
}
========= C code : File foo.c : END ===========


========= Compilation & Run : BEGIN =========

$ gcc -v
[---omitted---]
gcc version 3.3.1 (cygming special)

$ gcc -W -Wall foo.c

$ a
printf-1
// printf-3 missing

$ cat foobar
printf-2
fprintf(out_fp)

========= Compilation & Run : END ===========



=====================================
Alex Vinokur
mailto:[email protected]
http://up.to/alexvn
=====================================
 
Joined
Jan 24, 2009
Messages
1
Reaction score
0
I couldn't take no for an answer and dug a little deeper. At least for MS systems you can switch back and forth from stdout and redirected stdout:

printf("To Console\n");
f = freopen("out.txt","w",stdout);
printf("redirect to file\n");
f = freopen("CON", "w", stdout);
printf("back to console\n");

Enjoy!
David Schneider
 
Joined
Jan 11, 2013
Messages
1
Reaction score
0
How to print the stdout after using freopen..

Solution:

you can type these freopen ("/dev/tty", "a", stdout).
before that printf statement which you want to print in the stdout
Is this what you were trying to do :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top