c中的分段错误(核心转储)

时间:2016-11-14 11:39:56

标签: c csv strtok

我有一个代码,它将读取csv文件并将数据保存在缓冲区中。但我得到分段故障核心转储作为状态错误。

csv文件的内容是

#include<stdio.h>
#include<stdlib.h>



struct pattern_buffer {    //structure to store the contents of csv files 
    unsigned int x[1024];
    unsigned int y[1024];
    unsigned int z[1024];

}Data_buffer;

int main(void)
{
    char buffer[1024];

    char *record,*line;
    int x1=0,y1=0,z1=0,linecount=0; //linecount is used to check weather 1024 rows have been read or not

    int n=0;


    FILE *fstream = fopen("files.csv","r");
    if(fstream == NULL)             //check file 
    {
        printf("\n inside .so \n unable to open csv files \n");
        return 0;
    }
    printf("\n Sensor values are \n");

    line=fgets(buffer,sizeof(buffer),fstream);  //skip first line (weather it will skip the first line

    while((line=fgets(buffer,sizeof(buffer),fstream))!=NULL   &&  linecount<1024)
    {
        record=strtok(line,",");  //skip first column
        while(record!= NULL)
        {   
            //record=strtok(NULL,",");   //skip second column
            record=strtok(NULL,",");     //skip third column
            record=strtok(NULL,",");      //get x axis     
            Data_buffer.x[x1++]=atoi(record);
            record=strtok(NULL,",");         //get y axis     
            Data_buffer.y[y1++]=atoi(record);
            //record=strtok(NULL,",");        //get z axis     
            Data_buffer.z[z1++]=atoi(record);

        }
        linecount++;
    }
    return -1;
}

我读取和解析文件的代码是

{{1}}

所以请指定我天气我的逻辑是否正确跳过第一行并读取csv值。

1 个答案:

答案 0 :(得分:0)

抱歉,我找到了解决此问题的方法。

我没有包含在头文件中,所以strtok无法为我解析令牌。我在调试时检查了记录的值,但记录值为零。因此,当我研究了很多时,我才知道我没有包括哪些导致我错误。