C++中的freopen的用法实例详解
作者:xvhao2013
freopen用于文件输入输出,重定向stdin、stdout或stderr,常见用途包括重定向输入输出到文件,避免手动修改代码,示例代码展示了如何使用freopen实现a+b程序,并强调了错误处理、文件关闭等注意事项,感兴趣的朋友跟随小编一起看看吧
介绍:
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用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
