Redirecting standard streams | Xagasoft

Redirecting standard streams


      Sometimes you just have to redirect one of the standard streams, for example, if you want to log all output to a file, but don't have any good way of doing that for whatever reason. This technique can also be used to redirect the standard stream and create additional streams for child processes, and so on.

      #include <stdio.h>
      #include <unistd.h>
      #include <sys/stat.h>
      #include <fcntl.h>
      
      int main()
      {
      	// First we open a new file
      	int i2 = open("logfile.txt", O_WRONLY|O_CREAT|O_TRUNC, 0644 );
      	// Check for errors
      	if( i2 < 0 )
      	{
      		perror("open");
      		return 1;
      	}
      	// Now we redirect stdout to our new file.  We don't actually need to close
      	// stdout in order for this to work.
      	dup2( i2, STDOUT_FILENO );
      
      	// From now on, anything that would have gone to stdout will go into our
      	// log file.
      	printf("Hi there.\n");
      
      	return 0;
      }
      
      
       
      This page is copyright 2009-2010, Xagasoft, All rights reserved.