c-遍历txt文件的字段会导致分段错误

问题描述 投票:0回答:1

因此,我正在创建一个名为convert.c的程序,该程序从csv文件中获取数据并将数据写入新的名为data.bin的文本文件中(但对原始csv文件进行了更改)。 CSV文件的一个字段/列特别包含一列整数,这些整数已写入data.bin文件。在我的analyticsInjuries.c文件中,我试图编写一个程序,该程序读取data.bin文件并计算该特定列内的整数总数(代表飓风造成的伤害总数)。

我计算了convert.c文件中的受伤总数并将其打印在终端中。它确实起作用,但是当我尝试在analyserInjuries文件中执行相同操作时,它输出的值为0。我不确定为什么会发生这种情况,因为convert.c中的getfield函数和计算工作正常。

我相信char * two = getfield(buf,2)行有问题。因为当我尝试打印第二个字段中的所有值时,会导致分段错误。任何帮助,将不胜感激。我对analyzerInjuries.c文件出了什么问题真的感到困惑。

analyzeInjuries.c:

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

#define POINTER2INT(a) ((int)(intptr_t)(a))

char *getfield (char *buf, size_t field)
{
    size_t len = strlen(buf);       /* size of input string */
    char *cpy = malloc (len + 1),   /* allocate for copy */
        *p,                         /* pointer to use with strsep */
        *tok = NULL;                /* token for requested field */

    if (!cpy)                       /* validate allocation */
        return NULL;

    memcpy (cpy, buf, len + 1);     /* copy buf to cpy */
    p = cpy;                        /* pointer to cpy, preserves cpy address */

    while (field-- && (tok = strsep (&p, ","))) {}  /* get field field */

    /* copy tok to cpy and return cpy on success or NULL on failure */
    return tok ? memmove (cpy, tok, strlen(tok) + 1) : NULL;
}

int main (int argc, char **argv) {

    FILE *fd; 

    //Open the file for reading
    fd = fopen("data.bin", "r+");
    if(!fd){
        printf("ERROR: Could not open file\n");
        exit(1);
    }

    char c;
    int lineCount = 1090; //unsigned short int
    char buf[lineCount];

    int numDisast= 0;

    while (fgets (buf, lineCount, fd)) {
        char *second = getfield (buf, 3); //printing second field causes seg fault
        int field = POINTER2INT(second);
        numDisast = numDisast + field;


    }
    printf("%d\n", numDisast);
    return 0;
}

下图是data.bin文件的屏幕快照。红线表示我要查找其总和的字段。

enter image description here

我的data.bin文件基本上看起来像这样:

M         1         2        0        0        0.00
G         14         70        23        0        0.00
M         6         0        0        0        0.00
M         6         0        0        0        0.00
G         14         0        0        0        0.00
M         1         0        0        0        0.00
M         10         0        0        0        0.00

依此类推。

c pointers field fopen fread
1个回答
0
投票

我认为通过“打印第三字段会导致段错误”,是指尝试打印second变量。

getfield()如果找不到字段并且因为它使用,作为分隔符并且您的data.bin不使用,,则返回NULL,则它将始终返回NULL。然后,当您尝试打印它时,它将崩溃。

此外,您实际上并不是对列中的值求和。您的POINTER2INT宏不会将字符串转换为整数。您可能想改用atoi()

编辑

首先,您应该在循环中检查NULL:

char *second = getfield (buf, 3);
if (second) {
    printf("found field: %s\n", second);
}
else {
    printf("field not found\n");
}

第二,您的data.bin看起来可能使用制表符代替,作为分隔符。您可以在对","的调用中将"\t"更改为strsep(),看看是否有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.