Link to home
Start Free TrialLog in
Avatar of k23m
k23m

asked on

C++ redirect standard output for printf

Hi
I am building a small command shell in C++ in a Unix environment and I want to be able to redirect standard IO.  I have figured out how to do this for cout statements, but is there a simple way to do it for printf statements as well?  Thank you.
ASKER CERTIFIED SOLUTION
Avatar of g0rath
g0rath

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jkr
If you want to redirect/read the output of an external program, use 'popen()'. If you want to do that inside the code of a program, use 'freopen()', e.g.

/* FREOPEN.C: This program reassigns stderr to the file
 * named FREOPEN.OUT and writes a line to that file.
 */

#include <stdio.h>
#include <stdlib.h>

FILE *stream;

void main( void )
{
   /* Reassign "stderr" to "freopen.out": */
   stream = freopen( "freopen.out", "w", stderr );

   if( stream == NULL )
      fprintf( stdout, "error on freopen\n" );
   else
   {
      fprintf( stream, "This will go to the file 'freopen.out'\n" );
      fprintf( stdout, "successfully reassigned\n" );
      fclose( stream );
   }
   system( "type freopen.out" );
}