fopen版
#include <stdio.h>
#define INF 1000000000
int main(void)
{
FILE *fin, *fout; //定义文件类型
fin = fopen("data.in", "rb"); //定义文件名和文件操作
fout = fopen("data.out", "wb");
int x, n = 0, min = INF , max = -INF , s = 0;
while (fscanf(fin, "%d", &x) == 1) //使用文件输入
{
s+=x;
if (x < min) min=x;
if (x > max) max=x;
n++;
}
fprintf(fout, "%d %d %.3lf\n", min, max, (double)s/n); //使用文件输出
fclose(fin); //关闭文件读入读出状态
fclose(fout);
return 0;
}
相比freopen()函数来说,该函数使用起来代码繁杂,但比较灵活
C++中比较正规的输入输出
#include <fstream>
using namespace std;
ifstream fin("aplusb.in");
ofstream fout("aplusb.out");
int main()
{
int a,b;
while (fin >>a >> b)
fout << a+b << "\n";
return 0;
}