关闭

Freopen—C/C++文件输入输出利器

发表于:2015-2-16 09:27

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:FREE小宝    来源:51Testing软件测试网采编

  freopen以前经常使用,比较方便,可以当作模板,在中间替换为自己的代码即可使用。
  #include <stdio.h> // 实际使用中发现freopen也包含在iostream.h中,C++代码#include <iostream.h>即可。
  int main()
  {
  freopen("sample.in", "r", stdin);
  freopen("sample.out", "w", stdout);
  /* 同控制台输入输出 */
  fclose(stdin);
  fclose(stdout);
  return 0;
  }
  当我们求解acm题目时,通常在设计好算法和程序后,要在调试环境(例如VC 等)中运行程序,输入测试数据,当能得到正确运行结果后,才将程序提交到oj中。但由于调试往往不能一次成功,每次运行时,都要重新输入一遍测试数据,对于有大量输入数据的题目,输入数据需要花费大量时间。
  使用freopen函数可以解决测试数据输入问题,避免重复输入,不失为一种简单而有效的解决方法。
  函数名:freopen
  声明:FILE *freopen( const char *path, const char *mode, FILE *stream );
  所在文件: stdio.h
  参数说明:
  path: 文件名,用于存储输入输出的自定义文件名。
  mode: 文件打开的模式。和fopen中的模式(如r-只读, w-写)相同。
  stream: 一个文件,通常使用标准流文件。
  返回值:成功,则返回一个path所指定文件的指针;失败,返回NULL。(一般可以不使用它的返回值)
  功能:实现重定向,把预定义的标准流文件定向到由path指定的文件中。标准流文件具体是指stdin、stdout和stderr。其中stdin是标准输入流,默认为键盘;stdout是标准输出流,默认为屏幕;stderr是标准错误流,一般把屏幕设为默认。
  下面以在VC下调试“计算a+b”的程序举例。
C语法:
#include <stdio.h>
int main()
{
int a,b;
freopen("debug\\in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取
freopen("debug\\out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中
while(scanf("%d %d",&a,&b)!=EOF)
printf("%d\n",a+b);
fclose(stdin);//关闭文件
fclose(stdout);//关闭文件
return 0;
}
C++语法
#include <stdio.h>
#include <iostream.h>
int main()
{
int a,b;
freopen("debug\\in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取
freopen("debug\\out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中
while(cin>>a>>b)
cout<<a+b<<endl; // 注意使用endl
fclose(stdin);//关闭文件
fclose(stdout);//关闭文件
return 0;
}
21/212>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号