分段错误:11,读取文件和指针

时间:2014-03-19 21:17:48

标签: c

我正在制作一个从.txt文件中读取温度列表的程序。之后,我计算温度的变化,看看AC是否已经关闭或关闭。但是,每当我尝试运行程序时,我都会继续收到Segmentation Fault: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;
}

1 个答案:

答案 0 :(得分:0)

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

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