Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Stdout does not work after using freopen

Status
Not open for further replies.

waynejfoster

Programmer
Aug 7, 2001
13
0
0
GB
I'm using freopen to redirect stdin and stderr to files
the redirection is fine. The problem arises when I use
fclose to close the streams. This causes stdout to fail.

In the example below you will see the loop of 1000000
doing fprintf(stdout,"HELLO\n");
after redirection should have finished.

I don't get anything printing to the screen as I would have
expected. How do I restore stdout and stderr streams back
to the original state to enable me to carry on printing to the screen.

// redirect stdout to tmp_file for GCC output
if(!(stream=freopen(tmp_name,"a",stdout))){
fprintf(stderr,"Can't redirect stdout for GCC\n");
exit(EXIT_FAILURE);
}
// redirect stderr to tmp for GCC error output
if(!(estream=freopen(tmp_e_name,"a",stderr))){
fprintf(stderr,"Can't redirect stdout for GCC\n");
exit(EXIT_FAILURE);
}

// spawn command for GCC
_spawnlp(_P_WAIT,"gcc.exe","gcc.exe","-E","-I",library,in_name,NULL);
fclose(stream);
fclose(estream);

// THIS BIT DOES NOT PRINT TO THE SCREEN AS WOULD BE EXPECTED, WHY???

for(i=0;i<10000000;i++){
fprintf(stdout,&quot;HELLO\n&quot;);
}
 
It's ok i've found a solution.

using _dup to preseve the stdout and stderr handles

_dup2 to force the stdout and stderr to pointer to the
file handle in question

then _dup2 at the end to restore then old handles

so there yah go...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top