返回首页 C++ 模板

文件重定向与读写模板

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;
}

📖 要点说明

⚠️ 常见错误