文件重定向与读写模板
freopen 与 fstream——从文件读入、输出到文件
文件读写
freopen
fstream
重定向
GESP4
#include <bits/stdc++.h>
using namespace std;
int main() {
// ====== 方式一:freopen 重定向 ======
// 把 stdin/stdout 重定向到文件
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
// 现在 cin/cout 就是读写文件
int n;
cin >> n;
cout << n * 2 << endl;
// 关闭重定向(恢复控制台)
fclose(stdin);
fclose(stdout);
// ====== 方式二:fstream ======
ifstream fin("input.txt");
ofstream fout("output.txt");
if (!fin.is_open()) {
cerr << "无法打开文件" << endl;
return 1;
}
int x;
while (fin >> x) {
fout << x * 2 << endl;
}
fin.close();
fout.close();
return 0;
}
📖 要点说明
freopen最简单:重定向后 cin/cout 直接读写文件fstream更灵活:可同时操作多个文件- 打开文件后务必检查是否成功
- 竞赛中常用
freopen,本地测试用fstream
⚠️ 常见错误
freopen文件路径写错- 忘
fclose或close可能丢失缓冲数据 freopen后无法同时输出到控制台