• C文件操作


    文件操作步骤:

    1、创建文件指针

    2、关联文件

    3、操作文件

    4、关闭文件

    question: 求文件中数字的最大值、最小值、平均值

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <limits.h>
     4 
     5 int main()
     6 {
     7     int x, n=0, sum=0;
     8     int min=INT_MAX, max=INT_MIN;//click this link
     9     FILE *fin, *fout;//1、创建文件指针 
    10     
    11     //2、关联文件 
    12     fin  = fopen("data.in", "r");
    13     fout = fopen("data.out", "w");
    14     
    15     //3、操作文件 
    16     while(fscanf(fin, "%d", &x) == 1){
    17         sum += x;
    18         if(x<min) min=x;
    19         if(x>max) max=x;
    20         n++;
    21     }
    22     
    23     fprintf(fout, "min=%d
    max=%d
    avg=%.3lf
    ",
    24             min, max, (double)sum/n);
    25     
    26     //关闭文件 
    27     fclose(fin);
    28     fclose(fout);
    29     
    30     return 0;
    31 }

    补充:

    1、freopen用来重定义输入输出流

      重定义:改变标准输入输出流的含义

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <limits.h>
     4 
     5 int main() {
     6     int x,n=0,sum=0;
     7     int min=INT_MAX, max=INT_MIN;
     8 
     9     //重定义输入输出流 
    10     freopen("input.txt", "r", stdin);//freopen将stdin含义改变 
    11     freopen("output.txt", "w", stdout);
    12 
    13     while(scanf("%d",&x) == 1){
    14         sum += x;
    15         if(x<min)
    16             min=x;
    17         if(x>max)
    18             max=x;
    19         n++;
    20     }
    21     printf("min=%d
    max=%d
    avg=%.3lf
    ",
    22             min, max, (double)sum/n);
    23     return 0;
    24 }

    2、scanf / printf 是 fscanf / fpirintf 应用于 stdin / stdout 的特例

        即 fprintf(stdout, "%.3f ", 3.14159);

  • 相关阅读:
    Asp.Net MVC4开发二: Entity Framework在Asp.Net MVC4中的应用
    敌兵布阵(杭电1166)(树状数组)
    alibaba dexposed初步解析
    shell学习三十二天----read读取一行
    cocos2d-x CCScrollView 源代码分析
    语言-编程语言:Python
    GitHub:Python
    GitHub-Microsoft:DotNet4
    GitHub-Microsoft:DotNet3
    GitHub-Microsoft:DotNet2
  • 原文地址:https://www.cnblogs.com/guoyujiang/p/11901421.html
Copyright © 2020-2023  润新知