Home > database >  fscanf read another format in same file.csv
fscanf read another format in same file.csv

Time:05-26

My data file:

name/month/date/year
1.Moore Harris,12/9/1995
2.Ragdoll Moore,11/5/2022
3.Sax,Smart,3/1/2033
4.Robert String,9/7/204
bool success = fscanf(fptr, "%[^,]", nameEmploy) == 1;
bool success = fscanf(fptr, ",%d", &month) == 1;

I only can read 1,2,4 and then the program skips No.3. What should I use in this format to read it along with the other data?

CodePudding user response:

To parse the CSV file, it is recommended to read one line at a time with fgets() and use sscanf() to parse all fields in one call:

#include <stdio.h>
#include <string.h>

struct data {
    char name[32];
    int month, day, year;
};

int parse_csv(FILE *fp) {
    char buf[256];
    char c[2];
    struct data entry;
    int count = 0;

    while (fgets(buf, sizeof buf, fp)) {
        if (sscanf(buf, "1[^,],%d/%d/%d%1[\n]",
                   entry.name, &entry.month, &entry.day, &entry.year, c) == 5) {
            add_entry(&entry);
            count  ;
        } else {
            printf("invalid line: %.*s\n", (int)strcspn(buf, "\n"), buf);
        }
    }
    return count; 
}

Note however these shortcomings:

  • lines longer than 254 bytes will cause errors
  • fields cannot be quoted
  • the name field cannot contain ,
  • empty fields cannot be parsed by sscanf
  • Related