重定向方式访问文件

来源:互联网 发布:人工智能的应用 编辑:程序博客网 时间:2024/06/14 23:53
  • 使用文件最简单的方法是使用输入输出重定向,只需在main函数的入口处加入以下两条语句:
    freopen(“input.txt”, “r”, stdin);
    freopen(“output.txt”, “w”, stdout);
    上述语句讲使得scanf从文件input.txt读入,printf写入文件output.txt。事实上,不只是scanf和printf,所有的读键盘输入、写屏幕输出的函数都将改用文件。

  • 程序实例
    输入一些整数,求出它们的最小值、最大值和平均值(保留三位小数)。输入保证这些书都是不超过1000的整数。

//重定向方式读写文件:使所有的读写都改用文件 # define LOCAL # include <stdio.h># define INF 1000000int main(){    # ifdef LOCAL           freopen("d:\\datain.txt","r",stdin);    freopen("d:\\dataout.txt","w",stdout);    # endif    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;        n++;    }    printf("%d %d %.3f\n",min, max, (double)s/n);    return 0;}
0 0