重定向stdout到文件

本文介绍了两种将标准输出(stdout)重定向到文件的方法。第一种方法使用freopen函数将stdout指向一个文件;第二种方法利用dup和dup2系统调用进行重定向,并在完成后恢复原来的stdout。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

把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" );//没有会造成问题,需要小心
}

输出结果
[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]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值