您的位置:首页 > 运维架构

使用文件进行读取或输出的两种方式(重定向版和fopen版)

2018-03-12 12:06 295 查看
1.重定向版//利用文件进行读取和输出(重定向版)
//如果想要标准输入而文件输出时,只需将关于文件输入的语句注释掉即可,文件输入标准输出同理
//如果想回到标准输入输出时,只需将下一行的本地定义注释掉即可
#define LOCAL
#include<iostream>
#include<cstdio>
#include<fstream>
using namespace std;
int main()
{
#ifdef LOCAL
freopen("input.txt","r",stdin); //scanf从文件中读取
freopen("output.txt","w",stdout); //printf到文件
#endif // LOCAL
int x,n=0,min=100,max=-100,s=0;
while(scanf("%d",&x)==1)
{
s+=x;
if(min>x) min=x;
if(max<x) max=x;
n++;
}
printf("%d %d %.3f\n",min,max,(double)s/n);
return 0;
}2.fopen版//使用文件输入输出,但当禁止使用重定向的方式时,采用如下方法
//此时为文件读入,标准输出
#include<iostream>
#include<cstdio>
#include<fstream>
using namespace std;
int main()
{
FILE *fin,*fout;
fin=fopen("input.txt","rb"); //文件读取
//fout=fopen("output.txt","wb"); //输出到文件
//fin=stdin; //把fopen版的程序改成读写标准输入输出
fout=stdout;
int x,n=0,min=100,max=-100,s=0;
while(fscanf(fin,"%d",&x)==1) //scanf变为fscanf
{
s+=x;
if(min>x) min=x;
if(max<x) max=x;
n++;
}
fprintf(fout,"%d %d %.3f\n",min,max,(double)s/n); //printf变为fprintf
fclose(fin); //关闭两个文件
fclose(fout);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  文件读取及输出