重定向输入输出freopen,文件流fstream

函数名:freopen
声明:FILE *freopen( const char *path, const char *mode, FILE *stream );
参数说明
path: 文件名,用于存储输入输出的自定义文件名。
mode: 文件打开的模式。和fopen中的模式(如r-只读, w-写)相同。
stream: 一个文件,通常使用标准流文件。
返回值
成功,则返回一个path所指定文件的指针;失败,返回NULL。(一般不使用它的返回值)
功能:实现重定向,把预定义的标准流文件定向到由path指定的文件中。标准流文件具体是指stdin、stdout和stderr。其中stdin是标准输入流,默认为键盘;stdout是标准输出流,默认为屏幕;stderr是标准错误流,一般把屏幕设为默认。通过调用freopen,就可以修改标准流文件的默认值,实现重定向。

#include <iostream>
#include <cstdio>
using namespace std;

int main()
{
	char ch;
	freopen("in.txt", "r", stdin);
	freopen("out.txt", "w", stdout);
	while ((ch=getchar())!=EOF){
		putchar(ch);
	}
	fclose(stdin);
	fclose(stdout);
	return 0;
} 

C++文件流方式读写文件

#include <iostream>
#include <fstream>
using namespace std;

int main(){
	ifstream fin("C:\\Users\\dell\\Desktop\\1\\1.in");
	ofstream fout("C:\\Users\\dell\\Desktop\\1\\1.out");
	int t;
	while (fin>>t){
		fout<<t<<endl;
	}
	fin.close();
	fout.close(); 
	return 0;
}

C文件读写方式

#include <iostream>
#include <cstdlib>
using namespace std;

int main(){
	FILE *fin = fopen("C:\\Users\\dell\\Desktop\\1\\1.in", "r");
	FILE *fout = fopen("C:\\Users\\dell\\Desktop\\1\\1.out", "w");
	int t;
	while (fscanf(fin, "%d", &t)!=EOF){
		fprintf(fout, "%d", t);
	}	
	fclose(fin);
	fclose(fout);
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

H4ppyD0g

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值