文件操作

概念讲解

freopen 重定向

12345678910111213#include <cstdio>

int main() {
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
    
    // 正常使用 cin/cout
    
    fclose(stdin);
    fclose(stdout);
    
    return 0;
}

模式

模式 说明
"r" 只读
"w" 只写(覆盖)
"a" 追加

考点分析

初赛考查方式

  1. 选择题: freopen 用法
  2. 程序阅读: 文件操作
  3. 填空题: 模式参数

常见题型

  • freopen 用法
  • 文件读写

例题精讲

例题 1:freopen

题目: freopen 的作用是什么?

解答:

重定向输入输出到文件

例题 2:文件读写

题目: 如何从文件读取数据?

解答:

123freopen("input.txt", "r", stdin);
int a;
cin >> a;

练习题

  1. freopen 的三个参数分别是什么?
查看答案
1freopen(filename, mode, stream);
  • filename:文件名(如 "input.txt")
  • mode:打开模式("r" 读,"w" 写,"a" 追加)
  • stream:要重定向的流(stdin 或 stdout)
  1. 如何将输出写入文件?
查看答案
123freopen("output.txt", "w", stdout);
cout << "Hello, File!" << endl;
fclose(stdout);
  1. fclose 的作用是什么?
查看答案

fclose 用于关闭文件,释放资源。

12fclose(stdin);   // 关闭输入文件
fclose(stdout);  // 关闭输出文件

关闭文件后,不能再进行读写操作。

易错点

⚠️ 注意:

  1. freopen 要在所有输入输出之前
  2. 记得关闭文件
  3. 文件名要正确
  4. 竞赛中要记得取消注释