使用文件进行读取或输出的两种方式(重定向版和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;
}
//如果想要标准输入而文件输出时,只需将关于文件输入的语句注释掉即可,文件输入标准输出同理
//如果想回到标准输入输出时,只需将下一行的本地定义注释掉即可
#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;
}
相关文章推荐
- 使用字符流的方式进行文件的读取并打印至控制台
- springBoot使用Controller读取配置文件两种方式&读取自定义配置方法
- java使用文件或字节数组方式加载图片,并修改图片后进行保存、输出等
- java 读取文件——按照行取出(使用BufferedReader和一次将数据保存到内存两种实现方式)
- //使用字符流的方式进行文件HelloWorld.java的读取并打印至控制台
- 使用FileReader类、BufferedReader类、FileInputStream类三种方式进行文件的读取
- 使用Asp.net 生成 xml 文件,两种方式(DataSet和自定义模式)
- 使用libpng,libjpeg从文件读取和从内存读取2中方式的实现
- 读取配置文件[方式二]之使用Awk实现
- 按指定编码方式读取文件和输出文件
- 使用SQL Server 2005 新的语法ROW_NUMBER()进行分页的两种不同方式的性能比较
- log4j输出文件的两种配置方式
- [code]RCP中使用Servlet读取图片文件并输出
- 使用libpng,libjpeg从文件读取和从内存读取2中方式的实现
- java读取资源文件--使用文件流的方式读取
- spring中读取资源文件两种方式及应用场景
- 一个简单的系统配置文件使用DTD和XSD两种方式描述
- C#使用WINAPI进行读取写入配置文件_C#【编程联盟】
- 使用WebClient上传文件的两种方式
- 用Properties读取配置文件后,使用TreeMap对keys进行排序