为什么我的这个c函数中的getLine走得太远?

时间:2014-10-18 04:06:59

标签: c

void initializeCar(Car* v,char* mainFileIn)
{
    int counter = 0;
    int i = 0;
    FILE* fp = fopen(mainFileIn, "r"); 
    char* line = NULL;
    size_t len = 0;
    ssize_t read;
    char* pch;

    while((read = getline(&line, &len,fp)) != -1)
    {
        if(i == 50)
        {
            printf("Cannot hold more than 50 Cars.");
            exit(1);
        }

        pch = strtok(line,",");
        v[i].pid = ++counter;
        v[i].xLocation = (float)strtod(pch,NULL);

        printf("pch: %s\n",pch);

        pch=strtok(NULL,",");
        printf("pch: %s\n",pch);

        v[i].yLocation = (float)strtod(pch,NULL);

        pch = strtok(NULL,",");

        printf("pch: %s\n",pch);

        v[i].velocity = (float)strtod(pch,NULL);

        pch = strtok(NULL,",");

        printf("pch: %s\n",pch);

        v[i].angle = (int)strtol(pch,NULL, 10);
        v[i].start = NULL;
        i++;

    }
    free(line);
    fclose(fp);
}

由于某些原因,我的代码中的所有内容都有效,只是它在我的最后一行之后读取了一行,并给了我一个分段错误。我无法弄清楚为什么,因为我根据while教程之一对getLine循环进行了建模:http://man7.org/linux/man-pages/man3/getline.3.html

2 个答案:

答案 0 :(得分:3)

您的文件末尾可能有空行,导致pch为空。你的程序应该处理不包含逗号的行。

答案 1 :(得分:-1)

您正在捕捉行尾的\ n字符。