This is what I came up with for reading a csv file with multiple types. It seems to get the job done in all cases but 1,2,,"a". Where there is a blank space. Can I please have some ideas on how to fix this?
const char* getfield(char* line, int num)
{
const char* tok;
for (tok = strtok(line, ",");
tok && *tok;
tok = strtok(NULL, ",\n"))
{
if (!--num)
return tok;
}
return NULL;
}
while(fgets(line, 80, inputfp1) != NULL)
{
printf(" line is %s \n", line);
char* tmp1 = strdup(line);
char* tmp2 = strdup(line);
char* tmp3 = strdup(line);
char* tmp4 = strdup(line);
printf("Field 1 would be %s\n", getfield(tmp1, 1));
printf("Field 2 would be %s\n", getfield(tmp2, 2));
printf("Field 3 would be %s\n", getfield(tmp3, 3));
printf("Field 4 would be %s\n", getfield(tmp4, 4));
// NOTE strtok clobbers tmp
free(tmp1);
free(tmp2);
free(tmp3);
free(tmp4);
//sscanf(line, "%d, %d, %d, %d", &column1[i], &column2[i], &column3[i], &column4[i]);
//printf(" column1[i] is %d column2[i] is %d column3[i] is %d column4[i] is %d \n", column1[i], column2[i], column3[i], column4[i]);
i++;
memset(line, 0, 80);
}