printf的重定向与恢复

本文探讨了在Windows和Linux环境下如何实现printf的输出重定向,包括在多线程环境中如何管理和恢复输出流,以便在不同线程间控制打印信息的目的地。

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

把行信息打印到stdio窗口,然后再有一行到文件,接着又有一行到stdio屏幕。
先来看一个错误的例子




#include <ansi_c.h>
int main (int argc, char *argv[])
{
FILE *copy;




printf ("This is printed to screen!\n");
copy = stdout;
stdout = fopen ("stdio test.txt", "w");
printf ("This is printed to a file!\n");
fclose (stdout);
stdout = copy;
printf ("Where is this line?\n");
return 0;
}
类似于copy = stdout;直接的赋值是不可行的,应该要用dup,dup2,正确的应该是下面这样的




#include <stdio.h>
#ifdef unix
#include <unistd.h>
#endif
#ifdef WIN32
#include <io.h>  
#define fileno _fileno
#define dup2 _dup2




int main (int argc, char *argv[])
{
FILE *copy;
int bak_out = dup(1);// can use fileno(stdout) to repl
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值