重定向stdout到文件

重定向stdout到文件把 stdout 重定向到文件两种方法 第一种方法没有恢复通过 freopen 把 stdout 重新打开到文件 code java includeFILE stream voidmain void stream freopen freopen out w stdout 重定向 if stream

把stdout重定向到文件

两种方法:
第一种方法没有恢复

通过freopen把stdout重新打开到文件


#include

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-e5aaf.jpg[/img]
———————-
第二种方法使用dup复制
先把 1 复制出来
然后建立个文件,用fileno取到文件描述符 覆盖到1
所有对1的操作都输出到文件了
用完之后,再把开始复制出来的 用dup2还给 1


#include
#include
#include
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]
































版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/225152.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月17日 上午9:59
下一篇 2026年3月17日 上午9:59


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号