重定向stdout到文件

把stdout重定向到文件
两种方法:
第一种方法没有恢复

通过freopen把stdout重新打开到文件
#include <stdio.h>
 
FILE *stream;
void main( void )
{
   stream = freopen( "freopen.out", "w", stdout ); // 重定向

  if( stream == NULL )
     fprintf( stdout, "error on freopen\n" );
  else
  {
     //system( "type freopen.out" );
     system( "ls -l" );
     fprintf( stream, "This will go to the file 'freopen.out'\n" );
     fprintf( stdout, "successfully reassigned\n" );
     fclose( stream );
  }
     fprintf( stdout, "this is not print out\n" );//这里没有输出
  //system( "ls" );//没有会造成问题,需要小心
}

输出结果

----------------------
第二种方法使用dup复制
先把 1 复制出来
然后建立个文件,用fileno取到文件描述符 覆盖到1
所有对1的操作都输出到文件了
用完之后,再把开始复制出来的 用dup2还给 1
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> 
int main( )
{
   int old;
   FILE *new;
   old = dup( 1 );   // 取标准输出句柄  
   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 );
   }
   if( -1 == dup2( fileno( new ), 1 ) )//把文件的描述符给到1,1就不代表stdout了
   {
      perror( "Can't dup2 stdout" );
      exit( 1 );
   }
   system( "ls -l" );
   puts( "This goes to file 'data'\r\n" );
   fflush( stdout );
   fclose( new );
   dup2( old, 1 ); // 恢复
   puts( "This goes to stdout\n" );
   puts( "The file 'data' contains:" );
   //system( "type data" );
   system( "file data" );
}

输出结果

猜你喜欢

转载自haoningabc.iteye.com/blog/2026273