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

C语言freopen()函数:文件流重定向,流替换

时间:12-29来源:作者:点击数:110

头文件:#include <stdio.h>

freopen()函数用于文件流的的重定向,一般是将 stdin、stdout 和 stderr 重定向到文件。

所谓重定向,就是改变文件流的源头或目的地。stdout(标准输出流)的目的地是显示器,printf()是将流中的内容输出到显示器;可以通过freopen()将stdout 的目的地改为一个文件(如output.txt),再调用 printf(),就会将内容输出到这个文件里面,而不是显示器。 

freopen()函数的原型为:
    FILE *freopen(char *filename, char *type, FILE *stream);

【参数】filename为要重定向到的文件名;type为文件打开方式,请参考fopen()函数;stream为被重定向的文件流(一般是 stdin、stdout 或 stderr)。

【返回值】成功则返回指向filename文件的指针,否则返回NULL。

【实例】将标准输出流重定向到文件。

  • #include<stdio.h>
  • int main()
  • {
  • if(freopen("D:\\OUTPUT.txt","w",stdout)==NULL)
  • printf("重定向出错");
  • printf("重定向成功");
  • fclose(stdout);
  • return 0;
  • }

运行程序,如果重定向成功,D盘下会多出一个文件 OUTPUT.txt,文件内容为“重定向成功”。

又如,从文件in.txt中读入数据,计算加和输出到out.txt中。

  • #include<stdio.h>
  • int main()
  • {
  • freopen("in.txt","r",stdin);
  • freopen("out.txt","w",stdout);
  • int a,b;
  • while(scanf("%d%d",&a,&b)!=EOF)
  • printf("%d\n",a+b);
  • fclose(stdin);
  • fclose(stdout);
  • return 0;
  • }

如果要恢复默认的文件流,可以重新打开标准控制台设备文件,只是这个设备文件的名字是与操作系统相关的。

DOS/Win:
freopen("CON", "r", stdin);

Linux:
freopen("/dev/console", "r", stdin)

最后,给出一个重定向的模板:

  • #include <stdio.h>
  • int main()
  • {
  • freopen("slyar.in", "r", stdin);
  • freopen("slyar.out", "w", stdout);
  • /* 中间按原样写代码,什么都不用修改 */
  • fclose(stdin);
  • fclose(stdout);
  • return 0;
  • }

 

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