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