这是一种效率比较高的读入和输出方法;FILE 要大写,FILE *fin,fout;定义2个FILE类型的变量,习惯用fin fout;fopen函数打开相应的文件,fscanf()读入数据,fprintf()输出数据到文件。函数feof(fin)判断文件是否结束,返回值时真假。
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=100001;
int main()
{
FILE *fin,*fout;
int n,a[maxn];
fin=fopen("1.txt","r");
fout=fopen("2.txt","w");
fscanf(fin,"%d",&n);
for(int i=0;i<n;i++)
fscanf(fin,"%d",&a[i]);
sort(a,a+n);
for(int i=0;i<n;i++)
fprintf(fout,"%d ",a[i]);
return 0;
}
#include<iostream>
#include<fstream>
#include<cstdio>
using namespace std;
int main()
{
FILE *fin,*fout;
int a,sum;
fin=fopen("1.txt","r");
fout=fopen("2.txt","w");
sum=0;
while(!feof(fin))//函数feof(fin)判断文件是否结束,返回值是真假
{
fscanf(fin,"%d",&a);
sum+=a;
}
fprintf(fout,"%d",sum);
return 0;
}