介绍:
freopen常用于比赛中,是文件输入输出的意思。
写法:
freopen("输入文件名","r",stdin);
freopen("输出文件名","w",stdout);
下面用freopen写一个a+b。
cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
int a,b;
cin>>a>>b;
cout<<a+b;
return 0;
}
补充:
freopen 的基本概念
freopen 是 C/C++ 标准库中的一个函数,用于重定向标准输入(stdin)、标准输出(stdout)或标准错误(stderr)到指定的文件。通常在需要从文件读取输入或输出到文件时使用,避免手动修改大量代码中的输入/输出语句。
函数原型
cpp
FILE* freopen(const char* filename, const char* mode, FILE* stream);
- filename:目标文件名。
- mode :文件打开模式(如
"r"为读,"w"为写,"a"为追加)。 - stream :需要重定向的流(
stdin、stdout或stderr)。 - 返回值 :成功时返回流的指针,失败时返回
NULL。
常见用途
重定向标准输入到文件
cpp
freopen("input.txt", "r", stdin);
此后所有 scanf 或 cin 操作将从 input.txt 读取数据。
重定向标准输出到文件
cpp
freopen("output.txt", "w", stdout);
此后所有 printf 或 cout 操作将写入 output.txt。
示例代码
cpp
#include <cstdio>
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int a, b;
scanf("%d%d", &a, &b);
printf("%d\n", a + b);
fclose(stdin);
fclose(stdout);
return 0;
}
注意事项
- 错误处理 :检查
freopen返回值是否为NULL,避免文件打开失败导致未定义行为。 - 恢复默认流 :可通过重定向到
/dev/tty(Linux)或CON(Windows)恢复控制台输入/输出。 - 文件关闭 :显式调用
fclose关闭文件流,避免资源泄漏。
恢复标准流示例(Linux)
cpp
freopen("/dev/tty", "r", stdin); // 恢复标准输入
freopen("/dev/tty", "w", stdout); // 恢复标准输出
兼容性问题
- Windows 平台需使用
CON代替/dev/tty。 - 竞赛编程中常用
freopen简化文件输入/输出,但需注意平台差异。