Another CSV parsing question
Hello all,
I'm hoping I'm not beating a dead horse here (which is completely possible) but I am unable to figure out what I'm doing wrong with this CSV parsing code. I have a CSV file that has null fields, but will always have the commas for those fields. So, what we get is a file that has the current structure:
1,2,3,4,,,,,,6,7,,,7,8,,,8
It could also all be filled in:
1,2,3,4,5,6,7,8,9
They will always have the same number of columns though (even though my example did not). The code I'm using to parse this file is shown below:
Code:
#include <stdio.h> /* required for file operations */
#include <string.h>
FILE *fr; /* declare the file pointer */
main()
{
char line[2500];
char delims[] = ",";
char *result = NULL;
int count = 0;
fr = fopen ("testfile", "r");
/* fr = fopen ("tmpfile", "r"); open the file for reading */
/* elapsed.dta is the name of the file */
/* "rt" means open the file for reading text */
while(fgets(line, 2500, fr) != NULL)
{
if (line[0] == '#') {
continue;
}
result = strtok(line, delims);
while (result != NULL) {
if (count == 11) {
printf("result: %s\n", result);
count = 0;
} else {
count+=1;
}
result = strtok(NULL, delims);
}
count = 0;
}
fclose(fr); /* close the file prior to exiting the routine */
} /*of main*/
I've tested files with all the columns filled out in every line and this code seems to work. So I guess my question is, how do I test for a field having null characters such that I can print the REAL 11th field of the csv file's line? Hopefully this is a clear question, if you need any clarification, please let me know and I will provide as much data as I can!