介绍:

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:需要重定向的流(stdinstdoutstderr)。
  • 返回值:成功时返回流的指针,失败时返回 NULL

常见用途

重定向标准输入到文件
freopen("input.txt", "r", stdin);

此后所有 scanfcin 操作将从 input.txt 读取数据。

重定向标准输出到文件
freopen("output.txt", "w", stdout);

此后所有 printfcout 操作将写入 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用法内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

声明:本站(华域联盟www.cnhackhy.com)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。