mercredi 24 février 2016

CSV Parsing and Insert to Database - Null Values and Segmentation Fault

Im using the following code to parse a CSV and insert the values into a table

This is the CSV

me;val1;val2;val3;val4;val5;
me;val1;val2;val3;val4;val5;


void readcsv()
{
    FILE* stream = fopen("input.csv", "r");

    char line[1024];
    while (fgets(line, 1024, stream))
    {
        char* tmp = strdup(line);


    char * a1= getcsvfield(tmp, 1);
    char *b1= getcsvfield(tmp, 2);
    char *c1= getcsvfield(tmp, 3);
    char *d1= getcsvfield(tmp, 4);
    char *e1= getcsvfield(tmp, 5);
    char *f1= getcsvfield(tmp, 6);
        printf("Field 1 would be %s\n", a1);
        // printf("Field 2 would be %s\n", getcsvfield(tmp, 2));
        // printf("Field 2 would be %s\n", getcsvfield(tmp, 3));
        // printf("Field 2 would be %s\n", getcsvfield(tmp, 4));
        // printf("Field 2 would be %s\n", getcsvfield(tmp, 5));
        // printf("Field 2 would be %s\n", getcsvfield(tmp, 6));
        execute("INSERT INTO sdata  (sid,name,area,type,stbamount,pkgamount) VALUES('%s','%s','%s','%s','%s','%s');",a1,b1,c1,d1,e1,f1);
        // NOTE strtok clobbers tmp
        free(tmp);
    }
}
//Used for parsing CSV
const char* getcsvfield(char* line, int num)
{
    char buffer[1024]= {0};
    strcpy(buffer, line);

    const char* tok;
    for (tok = strtok(buffer, ";");
            tok && *tok;
            tok = strtok(NULL, ";\n"))
    {
        if (!--num)
            return tok;
    }
    return NULL;
}


ERROR:
Segmentation fault (core dumped)

The values are printed correctly.

Aucun commentaire:

Enregistrer un commentaire