-
December 3rd, 2002, 12:03 PM
#1
How to give back hand to screen in C ?
Hello everybody,
I have a little problem..
A program I'm modifying has the following behavior :
If an option is given, it will write information messages to the screen, but if an other option is given, it will write information messages to a File named LogFile.txt ...
Now, what's done in the code is this :
freopen("LogFile.txt", "a+", stdout);
To close stdout and assign LogFile.txt to the standard output.
After everything is done, I need to give back the hand to the screen to write a message about the success of the program, based on some text in an other file.
Everything I saw about the freopen function didn't talk about giving back the hand to the screen..
I use
freopen("NUL", "a+", stdout);
to close the stream stdout assigned to LogFile ( it is shared by a lot of programs called from the main one) , but I can't write anything on the screen from then on.
Does anybody know how I can write back to the screen without leaving the program ?
Thanks
Sylvain
Last edited by sylvain_nurun; December 3rd, 2002 at 02:02 PM.
-
October 23rd, 2003, 02:17 PM
#2
How to give back hand to screen - Answer
Hi I have been looking for this one for a while, the doc for freopen doesn't mention any of it however it can be found under _dup2 documentation.
Anyway here's the code from it:
/* DUP.C: This program uses the variable old to save
* the original stdout. It then opens a new file named
* new and forces stdout to refer to it. Finally, it
* restores stdout to its original state.
*/
#include <io.h>
#include <stdlib.h>
#include <stdio.h>
void main( void )
{
int old;
FILE *new;
old = _dup( 1 ); /* "old" now refers to "stdout" */
/* Note: file handle 1 == "stdout" */
if( old == -1 )
{
perror( "_dup( 1 ) failure" );
exit( 1 );
}
write( old, "This goes to stdout first\r\n", 27 );
if( ( new = fopen( "data", "w" ) ) == NULL )
{
puts( "Can't open file 'data'\n" );
exit( 1 );
}
/* stdout now refers to file "data" */
if( -1 == _dup2( _fileno( new ), 1 ) )
{
perror( "Can't _dup2 stdout" );
exit( 1 );
}
puts( "This goes to file 'data'\r\n" );
/* Flush stdout stream buffer so it goes to correct file */
fflush( stdout );
fclose( new );
/* Restore original stdout */
_dup2( old, 1 );
puts( "This goes to stdout\n" );
puts( "The file 'data' contains:" );
system( "type data" );
}
Output
This goes to stdout first
This goes to file 'data'
This goes to stdout
The file 'data' contains:
This goes to file 'data'
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|