I am using this code to parse a .csv file in C.
It works if the fields are in this format
ENTRY1,ENTRY2,ENTRY3,ENTRY4
or even if there are commas here:
ENTRY1, ENTRY2, ENTRY3, ENTRY4
However, if after an entry and before a comma there is a space, the program crashes. Like so: ENTRY1 ,ENTRY2,ENTRY3,ENTRY4
CODE:
#include <stdio.h>
#include <string.h>
int main()
{
        FILE *input_fp =fopen("file", "r");
        char buf[100];
        while (fgets(buf, sizeof buf, input_fp) != NULL) {
                char field1[30], field2[30], field3[30], field4[30];
#define VFMT " %29[^ ,\n\t]" //Defines limit of one entry to be 30 characters
                int n; // Use to check for trailing junk
                if (4 == sscanf(buf, VFMT "," VFMT "," VFMT "," VFMT " %n", field1, field2,
                                field3, field4, &n) && buf[n] == '\0') {
                        // Suspect OP really wants this wfield1th to be 1 more
                        if (printf("%s %s %s %s\n", field1, field2, field3, field4) < 0)
                                break;
                } else
                        break; // format error
        }
        fclose(input_fp);
return 0;
}
Example run: file contains:
ENTRY1, ENTRY2, ENTRY3, ENTRY4
ENTRY5,ENTRY6,ENTRY7,ENTRY8
ENTRY5 , ENTRY6, ENTRY7, ENTRY8
ENTRY1, ENTRY2, ENTRY3, ENTRY4
the output is:
ENTRY1 ENTRY2 ENTRY3 ENTRY4
ENTRY5 ENTRY6 ENTRY7 ENTRY8
it stops before concluding the third line and exits.
 
    