C 语言

关注公众号 jb51net

关闭
首页 > 软件编程 > C 语言 > C++ freopen用法

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);

常见用途

重定向标准输入到文件
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;
}

注意事项

恢复标准流示例(Linux)

freopen("/dev/tty", "r", stdin);  // 恢复标准输入
freopen("/dev/tty", "w", stdout); // 恢复标准输出

兼容性问题

到此这篇关于C++中的freopen的用法实例详解的文章就介绍到这了,更多相关C++ freopen用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文