2025年4月2日 星期三 乙巳(蛇)年 正月初三 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

怎样恢复一个重定向了的标准流?

时间:12-30来源:作者:点击数:105

如果要将重定向了的标准流恢复到初始状态,可以使用标准C库函数dup()和fdopen()。

dup()函数可以复制一个文件句柄,你可以用dup()函数保存对应于stdout标准流的文件句柄。fdopen()函数可以打开一个已用dup()函数复制了的流。这样,你就可以重定向并恢复标准流,请看下例:

  • #include <stdio.h>
  • void main(void);
  • void main(void)
  • {
  • int orig-stdout;
  • /* Duplicate the stdout file handle and store it in orig_stdout. */
  • orig_stdout = dup (fileno (stdout));
  • /* This text appears on-screen. */
  • printf("Writing to original stdout... \n") ;
  • /* Reopen stdout and redirect it to the "redir. txt" file. */
  • freopen("redir.txt", "w", stdout);
  • /* This text appears in the "redir. txt" file. */
  • printf("Writing to redirected stdout.., \n");
  • /* Close the redirected stdout. */
  • fclose (stdout);
  • /* Restore the original stdout and print to the screen again. */
  • fdopen(orig_stdout, "w" );
  • printf("I'm back writing to the original stdout. \n");
  • }

 

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门