freopen()实现标准输入流标准输出流重定向

1.头文件

stdio.h或者cstdio

2.声明

FILE *freopen(const char *filename,const char *mode,FILE *stream)

3.参数

* filename 文件名,用于存储输入输出的自定义文件名

* mode 文件打开的模式。和fopen中的模式相同

r -"只读访问" w - "只写访问" a - "追加写入"

*stream 一个文件,通常使用标准流文件

stdin - "标准输入" stdout - "标准输出" stderr - "标准错误"

4.功能

实现重定向,把与定义的标准流文件定向到由path指定的文件中。

标准流文件具体是指 stdin/stdout和stderr。

stdin标准输入流,默认是键盘

stdout标准输出流,默认是屏幕

stderr标准错误流,默认是屏幕

5.实例

(1)stdout到一个文本文件的重定向,把输出到屏幕的文本输出到一个文本文件中。

#include <iostream>

#include <cstdio>

using namespace std;


int main()

{

if(freopen("./output.txt","r",stdout)==NULL)

fprintf(stderr,"error redirecting stdout\n");


for(int i=0;i<10;i++)

printf("%3d",i);


printf("\n");

fclose(stdout);


return 0;

}

(2)从文件in.txt中读入数据,打印到屏幕上

#include <iostream>

#include <cstdio>


int main()

{

int a,b;

freopen("./in.txt","r",stdin);

while(cin >> a >> b)

cout << a+b <<endl;

fclose(stdin);

return 0;

}

(3)从文件in.txt中读入数据,计算加输出到out.txt中

#include <iostream>

#include <cstdio>

using namespace std;


int main()

{

int a,b;

freopen("./in.txt","r",stdin);

freopen("out.txt","a",stdout);

while(cin >> a >> b)

cout << a+b << endl;

fclose(stdin);

fclose(stdout);

return 0;

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值