首页 > 解决方案 > 尝试解析 excel 样式 .CSV 文件时出现分段错误 [C 编程]

问题描述

在本周的大部分时间里,我一直被困在这个项目上,而我一直在努力解决语法错误。

该项目的要点是通读标题并在某个列处停止并找到某些特征,例如该列的最小值、最大值和平均值。但是,我在为这项工作分配内存时遇到了困难。到目前为止,我一直无法进一步完善我的代码,因为我不断收到一个错误标签Segmentation Fault: 11

粗体部分是我将问题缩小到的部分。我知道存在内存问题,但我不明白为什么 fgets 没有从函数内读取文件的第一行。该文件也不返回 NULL 并且能够被访问。动态数组是一种选择,但我是初学者,对它们非常不熟悉。


double getMin(char csvfile[], char column[])
{
    int counter= 0;
    int counter2= 0;
    char* token;
    char type;
    char activity[20];
    int chap, sec;
    int min = -1000;
    char header[20];
    char *res;
char row[3000];
char Toprow[3000];

    sscanf(column, "%c%d.%d", &type, &chap, &sec);
    if (type!='P' && type!='C' && type!='L') return -2.0;
    if (chap<=0 || sec<=0) return 0;

    if(type == 'c' || type == 'C'){
        sprintf(activity,"%challange", type);
    }
    else if(type == 'P' || type == 'p'){
        sprintf(activity,"%carticipation", type);
    }
    else {
        sprintf(activity,"%cab", type);
    }

    sprintf(header, "%d.%d - %s", chap, sec, activity);

    FILE*  inFile = NULL;
   inFile = fopen("array.csv","r"); 
    //This is where the trouble begins that Ive narrowed down to 

    while(!feof(inFile)){
        fgets(Toprow, 3000, inFile);
        while(token != NULL){
            counter = counter + 1;
            token = strsep(&Toprow, ",");
            printf("%s", token);
            res = strstr(token, header);
            if(res){
            break;
                token = NULL;
                }
            }
    } 
        while (!feof(inFile)) {
            int currVal= 0;
            fgets(row, 3000, inFile);
            if(feof(inFile)) break;
            while( (token = strsep(&row, ','))  != NULL){
                ++counter2;
                    if(counter2 == counter){
                        res = strstr(token, header);
                        if(!res){
                        int currVal = atoi(*token);
                            if(currVal > min)
                                min = currVal;
                        counter2 = 0;
                        break;
                        }
                    }

                }
        }
    return min;
}

excel 文件看起来像这样以供参考在此处输入图像描述

标签: ccsvfile-iofgetsstrsep

解决方案


推荐阅读