noobatrilla noobatrilla - 1 year ago 105
C Question

Parsing CSV file by splitting with strsep

I'm getting some unwanted output when attempting to parse a comma seperated value file with strsep(). It seems be be working for half of the file, with a number with only one value (ie. 0-9), but as soon as multiple values are added like for instance 512,

It will print 512 12 2 512 12 2 and so on. I'm not exactly sure if this is due to the particular style that I'm looping? Not really sure.

int main() {

char line[1024];

FILE *fp;

int data[10][10];

int i = 0;
int j = 0;

fp = fopen("file.csv", "r");

while(fgets(line, 1024, fp)) {

char* tmp = strdup(line);
char* token;
char* idx;

while((token = strsep(&tmp, ","))) {

for (idx=token; *idx; idx++) {
data[i][j] = atoi(idx);
j++;
}
}
i++;
j=0;

free(tmp);

}


for(i = 0; i < 10; i++) {

for(j = 0; j < 10; j++) {
printf("%d ", data[i][j]);
}
printf("\n");
}

fclose(fp);
}

Answer Source

It is because you are creating elements by using every characters in the token returned by strsep() as start via the loop

for (idx=token; *idx; idx++) {
        data[i][j] = atoi(idx);
        j++;
}

Stop doing that and create just one element from one token to correct:

while((token = strsep(&tmp, ","))) {

        data[i][j] = atoi(token);
        j++;
}

Also free(tmp); will do nothing because tmp will be set to NULL by strsep(). To free the buffer allocated via strdup(), keep the pointer in another variable and use it for freeing.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download