_Zora. 2021-12-29 23:08 采纳率: 75%
浏览 53
已结题

C语言中文件操作为什么在函数调用中读不了文件内容?

不知道为什么在select函数中读不了文件的内容,也不知道程序哪里错了,救救孩子吧,孩子已经改了一天都找不到错误在哪里,如果能帮忙指点,一定会积极采纳!谢谢啦!!!

img

img

img

img

-

  • 写回答

2条回答 默认 最新

  • qzjhjxj 2021-12-30 17:15
    关注

    修改如下,供参考:

    #include <stdio.h>
    #include <stdlib.h>
    #include <cstdio>
    struct  huanjingcanshu {
        int   month;
        int   date;
        float temperature;
        float humidity;
        float lux;
        float ph;
    };
    double select(FILE* f2,int month) 
    {
         
        //rewind(f2); 
        struct huanjingcanshu b[3]; 
        int i,j=0; 
        double aver = 0;
        for(i=0;i<3;i++) 
        { 
            fread(&b[i], sizeof(struct huanjingcanshu), 1, f2);
            printf("%d %d %f %f %f %f\n",b[i].month,b[i].date,b[i].temperature,b[i].humidity,b[i].lux,b[i].ph); 
            if(b[i].month==month) 
            {
                aver += b[i].temperature;
                j++;
            } 
        } 
        if (j != 0)
            aver=aver/j;
        //fclose(f2); 
        return aver; 
    } 
    void input_data()
    {
        int i;
        struct huanjingcanshu a[3];
        FILE* fp = fopen("d:\\record.dat", "wb");
        if (NULL == fp)
        {
            printf("打开失败\n");
            exit(0);
        }
        printf("请输入具体数值\n");
        for (i = 0; i < 3; i++)
        {
            scanf("%d %d %f %f %f %f", &a[i].month, &a[i].date, &a[i].temperature, &a[i].humidity, &a[i].lux, &a[i].ph);
            fwrite(&a[i], sizeof(struct huanjingcanshu), 1, fp);
        }
        fclose(fp);
    }
    int main() 
    { 
        double aver;
        char   ch;
        int    i, mon, jj = 0;
        FILE* fp;
        while(1)
        { 
            printf("初始化:s  查询:g  退出:q\n"); 
            scanf(" %c", &ch);
            getchar();
            if (ch == 'q') {
    
                break;
                //exit(0);
            } 
            else if(ch=='g'){
                printf("请输入月份\n");
                scanf("%d", &mon);
                fp = fopen("d:\\record.dat", "rb");
                if (NULL == fp)
                {
                    printf("打开失败\n");
                    break;              //exit(0);
                }
                aver = select(fp, mon);
                fclose(fp);
                printf("月平均气温为:%lf\n", aver);
            }
            else if (ch == 's') {
                input_data();
            }
        } 
        return 0; 
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 1月7日
  • 已采纳回答 12月30日
  • 创建了问题 12月29日

悬赏问题

  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因