一、文件重定向 freopen从键盘输入数据称为标准输入stdin,
显示器输出数据称为标准输出stdout。
将stdin和stdout重新定向到某个文件中,使原来标准的输入输出变成指定文件的输入输出,这种文件操作的方式称为文件重定向。
文件重定向的实现步骤:
① 准备输入文件和输出文件,必须与当前程序cpp文件在同一目录下;
② 在程序里打开输入文件和输出文件,文件名和读写模式都是字符串,需要使用双引号包含,代码格式如下:
③ 编写程序功能的实现代码:
以读取方式打开输入文件 freopen(“test.in”,”r”,stdin);
以写入方式打开输出文件 freopen(“test.out”,”w”,stdout);④ 在程序的最后,关闭输入输出文件(使用函数fclose关闭文件)。
•关闭输入文件 fclose(stdin);
•关闭输出文件 fclose(stdout);
综上①②③④所述 ,完整的代码模板如下:
#include<bits/stdc++.h>//文件重定向代码模板
using namespace std;
int main(){
freopen("title.in","r",stdin);//文件输入,文件名自定义
freopen("title.out","w",stdout);//文件输出,文件名自定义
//此处开始写输入、输出代码
//信息学竞赛中,最后的文件关闭操作可以省略
return 0;
}
二、文件重定向 ifstream/ofstream
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ifstream ifs("test0.in");// 以读取方式打开
ofstream ofs("test0.out");// 以读取方式打开
if(ifs){ // 确保文件是否打开成功
string s;
getline(ifs, s);//读入一行,注意区分 ifs>>s
ofs<<s<<endl;
getline(ifs, s);
ofs<<s<<endl;
ifs.close(); // 关闭文件
}else // 否则
ofs << "Unable to open the file !" << endl;
return 0;
}
//2、上面是定义时打开文件,下面是open()方法打开文件
#include<iostream>
#include<fstream>
using namespace std;
int main(){
ifstream fin;// 以读取方式打开
fin.open("test0.in");// 以读取方式打开
ofstream fout;// 以读取方式打开
fout.open("test0.out");
if(fin){ // 确保文件是否打开成功
string s;
getline(fin, s);//读入一行,注意区分 fin>>s
fout<<s<<endl;
getline(fin, s);
fout<<s<<endl;
fin.close(); // 关闭文件
}else // 否则
fout<< "Unable to open the file !" << endl;
return 0;
}