c - 读取文件和指针时出现段错误 : 11,

标签 c

我正在编写一个程序,从 .txt 文件中读取温度列表。之后,我计算温度的变化,看看空调是否已关闭或关闭。但是,每当我尝试运行我的程序时,我都会继续收到 Segmentation Failure: 11 错误。我不知道为什么会发生这种情况。我想也许是因为我需要关闭正在打开的 *fp 文件。除此之外我不知道还有什么问题。

#include <stdio.h>
#define NUMTEMPS 2881


int main(void){

    //opening the file with temperatures
    FILE *fp;
    fp = fopen("temp.txt", "r");


    //Declaring variables
    int i,j;
    int pct, num30 = 0, count_ac_h = 0, count_ac_t = 0, current_h = 0;
    int ac_on = 0, count_ac = 0;
    double temps[2881], pct_hr[24], diff, current_temp, previous_temp;



    //Checking the temperature from the .txt file and counting the occurences
    for (i = 0; i < NUMTEMPS; ++i){
        fscanf(fp, "%lf", &temps[i]);
    }

    previous_temp = temps[0];
    for (i = 0; i < NUMTEMPS; ++i){
        if (num30 == 120){
            count_ac_t += count_ac_h;
            pct_hr[current_h] = (double)(count_ac_h/120);
            current_h++;
            count_ac_h = 0;
            num30 = 0;
        }

        current_temp = temps[i];
        diff = previous_temp - current_temp;
        if(diff > -0.5 && diff <0.5){
            if(ac_on == 1){
                count_ac_h++;
            }
        }

        else if (diff <= -0.5){
            if (ac_on == 0){
                ac_on = 1;
            count_ac_h++;
            }
        }

        else if (diff >= 0.5){
            if(ac_on == 1)
                ac_on = 0;
        }

        num30++;
        previous_temp = current_temp;
    }


    // Creating the bar graph based on results from above
    double pct_day = (double)(count_ac/NUMTEMPS);

    for (i = 20; i >= 0; i--){
        pct = i*5;
        for (j = 0; j < 24; ++j){
            if (pct > (pct_hr[i]*100))
                printf("_");
            else
                printf("*");
        }
    printf("\n");
    }

    return 0;
}

最佳答案

在 fopen() 之后,您永远不会检查 fp 是否为有效的文件指针(!= NULL)。

不太可能(实际上,我敢打赌)你的程序只是找不到它的数据文件。

关于c - 读取文件和指针时出现段错误 : 11,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22518315/

相关文章:

c++ - 快速定点 pow、log、exp 和 sqrt

c++ - C 和 C++ 中整数/算术类型的大小保证

c - 如何让阻塞在 recv() 上的线程优雅地退出?

c - 如何为 CreateProcess() 启动的进程设置语言环境

c - 在 C 中使用 fgets 从文件中读取字符串

c - Erlang:是否有与 C 预处理器 ## 指令等效的指令?

有人可以帮我完成管道上的这项作业吗?

c++ - linux C++ 通知文件类型创建

c - Fseek 到行号(具有可变长度的行)

c++ - 在 C 结构中定义 C++ 函数