把stdout重定向到文件
两种方法:
第一种方法没有恢复
通过freopen把stdout重新打开到文件
输出结果
[img]http://dl2.iteye.com/upload/attachment/0094/5100/ab6c3892-cc38-3d7f-be86-e5aa9546628f.jpg[/img]
----------------------
第二种方法使用dup复制
先把 1 复制出来
然后建立个文件,用fileno取到文件描述符 覆盖到1
所有对1的操作都输出到文件了
用完之后,再把开始复制出来的 用dup2还给 1
输出结果
[img]http://dl2.iteye.com/upload/attachment/0094/5098/2906b24b-49b8-36fe-9cc4-4b209d90ef87.jpg[/img]
两种方法:
第一种方法没有恢复
通过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" );//没有会造成问题,需要小心
}
输出结果
[img]http://dl2.iteye.com/upload/attachment/0094/5100/ab6c3892-cc38-3d7f-be86-e5aa9546628f.jpg[/img]
----------------------
第二种方法使用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" );
}
输出结果
[img]http://dl2.iteye.com/upload/attachment/0094/5098/2906b24b-49b8-36fe-9cc4-4b209d90ef87.jpg[/img]