使用fgets和sscanf读取逗号分隔的文件行

时间:2015-03-30 17:20:19

标签: c file

编辑(更多信息): 这部分代码初始化了结构。这是全球性的。

struct csvVars
{
    int timeStamp[500];
    int xAccel[500];
    int yAccel[500];
    int zAccel[500];
    int xGyro[500];
    int yGyro[500];
    int zGyro[500];
};

struct csvVars *userVars;

这是我找到用户条件的函数。从使用printf我可以确定程序在sscanf部分崩溃。

void userCondition()
{
    FILE *csvFile = fopen("C:\\user.csv", "r");
    if (csvFile == NULL)
    {
        printf("Error opening file ! \n");
        return;
    }


    char line[100];
    int i = 0, j;
    double average;
    double xAver = 0, yAver = 0, zAver = 0;


    //skips first line
    fgets (line, 100, csvFile);

    fgets (line, 100, csvFile);

    while(!feof(csvFile))
    {
        printf("111");
        sscanf(line, "%d,%d,%d,%d,%d,%d,%d", &userVars->timeStamp[i], &userVars->xAccel[i], &userVars->yAccel[i], &userVars->zAccel[i], &userVars->xGyro[i], &userVars->yGyro[i], &userVars->zGyro[i]);
        fgets (line, 100, csvFile);
        i++;
    }

    for (j = 0; j < i; j++)
    {
        xAver += userVars->xAccel[j];
        yAver += userVars->yAccel[j];
        zAver += userVars->zAccel[j];
    }

    xAver = xAver/(i+1);
    yAver = yAver/(i+1);
    zAver = zAver/(i+1);

    printf("%lf\n", xAver);
    printf("%lf\n", yAver);
    printf("%lf\n", zAver);

    fclose(csvFile);
}

这是一个示例文件行:

11201,2614,2441,2300,1854,978,1370

解决方案:

void userCondition()
{
    FILE *csvFile = fopen("C:\\user.csv", "r");
    char line[200];
    int i = 0, j;
    double xAver = 0, yAver = 0, zAver = 0;

    struct csvVars userVars;

    //skips first line
    fgets (line, 100, csvFile);

    fgets (line, 100, csvFile);

    while(!feof(csvFile))
    {
        sscanf(line, "%d,%d,%d,%d,%d,%d,%d", &userVars.timeStamp[i], &userVars.xAccel[i], &userVars.yAccel[i], &userVars.zAccel[i], &userVars.xGyro[i], &userVars.yGyro[i], &userVars.zGyro[i]);
        i++;
        fgets (line, 100, csvFile);
    }

    for (j = 0; j < i; j++)
    {
        xAver += userVars.xAccel[j];
        yAver += userVars.yAccel[j];
        zAver += userVars.zAccel[j];
    }

    xAver = xAver/(i+1);
    yAver = yAver/(i+1);
    zAver = zAver/(i+1);

    printf("%lf\n", xAver);
    printf("%lf\n", yAver);
    printf("%lf\n", zAver);

    fclose(csvFile);
}

1 个答案:

答案 0 :(得分:3)

第1步。更改:

sscanf(line, "%d,%d,%d,%d,%d,%d,%d", userVars->timeStamp[i], userVars->xAccel[i], userVars->yAccel[i], userVars->zAccel[i], userVars->xGyro[i], userVars->yGyro[i], userVars->zGyro[i]);

为:

sscanf(line, "%d,%d,%d,%d,%d,%d,%d", &userVars->timeStamp[i], &userVars->xAccel[i], &userVars->yAccel[i], &userVars->zAccel[i], &userVars->xGyro[i], userVars->yGyro[i], &userVars->zGyro[i]);

第2步。了解如何打开编译器警告(例如gcc -Wall),打开它们,并注意编译器告诉您的任何内容。永远不要编译而不启用警告。这可以为您节省大量的时间来处理这个特定错误,并且将来会继续为您节省大量时间。