一、重定向:
使用文件最简单的方法是使用输入输出重定向,只需在main函数的入口处加入以下两条语句:
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
上述语句将使得scanf从文件input.txt读入,printf写入文件output.txt。事实上,不只是scanf和printf,所有读键盘输入、写屏幕输出的函数都将改用文件。
代码举例:
#define LOCAL
#include <stdio.h>
#define INF 1000000000
int main()
{
#ifdef LOCAL
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif // LOCAL
int x, n = 0, min = INF, max = -INF, s = 0;
while(scanf("%d, &x") == 1){
s += x;
if(x < min) min = x;
if(x > max) max = x;
printf("x = %d, min = %d, max = %d\n", x, min, max);
n++;
}
printf("%d %d %.3f\n", min, max, (double)s / n);
return 0;
}
注:在本机调试运行时,只需将第一行的"#define LOCAL"注释掉即可,在OJ上提交时取消注释。
二、fopen:
在算法竞赛中,如果不允许使用重定向方式读写数据,应使用fopen和fscanf/fprintf进行输入输出。
代码举例:
#include <stdio.h>
#define INF 1000000000
int main()
{
FILE *fin, *fout;
fin = fopen("data.in", "rb");
fout = fopen("data.out", "wb");
// fin = stdin;
// fout = stdout;
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 %.3f\n", min, max, (double)s / n);
fclose(fin);
fclose(fout);
return 0;
}
注:在本机调试时,如果想把fopen版的程序改成读写标准输入输出,只需赋值“fin = stdin;fout = stdout;” 即可,不要调用fopen和fclose。
三、总结比较
重定向和fopen两种方法各有优劣。重定向的方法写起来简单、自然,但是不能同时读写文件和标准输入输出;fopen的写法稍显繁琐,但是灵活性比较大(例如,可以反复打开并读写文件)。