freopen 使用 --重定向文件
code:
#include <stdio.h> #define LOCAL #define NIF 1000000000 int main(){ #ifdef LOCAL freopen("in_data.txt","r",stdin); freopen("out_data.txt","w",stdout); #endif int x,n = 0,min = NIF,max = -NIF,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 %0.3f\n",min,max,(double)s/n); return 0; return 0; }
首先在相对路径中建立in_data.txt,然后再里面输入数据,相当于你在输入流中输入输出,只不过他是重定向到in_data.txt文件了,然后输出结果时,他又重定向到文件
ouot_data.txt文件中。
应用:在acm竞赛中,常常需要输入大量的输出,而我们如果每次在控制端输入的话,会花费大量的时间。而如果我们将其放入到文件中,我们就可以保存下来,然后进行测量大量的数据,而不用话费大量的时间。
其他应用,暂未挖掘。
在介绍另外一种方法把,原理类似的,采用fopen的方式来读写文件
code:
#include <stdio.h> #define NIF 1000000000 int main(){ FILE *fin,*fout; fin = fopen("in1_data.txt","rb"); fout = fopen("out1_data.txt","wb"); int x,n = 0,min = NIF,max = -NIF,s=0; while(fscanf(fin,"%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++; } fprintf(fout,"%d %d %0.3f\n",min,max,(double)s/n); fclose(fin); fclose(fout); return 0; }
若想把fopen 版的程序改写成读写标准输入输出,只需输入 fin = stdin,fout = stdout即可,不需要调用fopen和fclose