介绍:
freopen常用于比赛中,是文件输入输出的意思。
写法:
freopen("输入文件名”,“r”,stdin);
freopen("输出文件名”,“w”,stdout);
下面用freopen写一个a+b。
#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)到指定的文件。通常在需要从文件读取输入或输出到文件时使用,避免手动修改大量代码中的输入/输出语句。
函数原型
file* freopen(const char* filename, const char* mode, file* stream);
- filename:目标文件名。
- mode:文件打开模式(如
"r"为读,"w"为写,"a"为追加)。 - stream:需要重定向的流(
stdin、stdout或stderr)。 - 返回值:成功时返回流的指针,失败时返回
null。
常见用途
重定向标准输入到文件
freopen("input.txt", "r", stdin);
此后所有 scanf 或 cin 操作将从 input.txt 读取数据。
重定向标准输出到文件
freopen("output.txt", "w", stdout);
此后所有 printf 或 cout 操作将写入 output.txt。
示例代码
#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)
freopen("/dev/tty", "r", stdin); // 恢复标准输入
freopen("/dev/tty", "w", stdout); // 恢复标准输出
兼容性问题
- windows 平台需使用
con代替/dev/tty。 - 竞赛编程中常用
freopen简化文件输入/输出,但需注意平台差异。
到此这篇关于c++中的freopen的用法实例详解的文章就介绍到这了,更多相关c++ freopen用法内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论