simple csv parse
30/10/2019
I store purchases I make in a spreadsheet. The spreadsheet is becoming a pain to use so I am creating a program to store them in a database and prettyprint purchases.
The first piece needed was to parse the csv output of the spreadsheet, I did this with a simple C program:
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> struct purchase { char *product; char *website; char *date; char *cost; char *notes; }; void parsepurchase(struct purchase *p, char *line) { char *modline; char *bup; size_t linesize; size_t len; linesize = strlen(line); modline = malloc(linesize + 1); bup = modline; strcpy(modline, line); modline = strtok(modline, ",\""); p->product = malloc(strlen(modline) + 1); strcpy(p->product, modline); modline = strtok(NULL, ",\""); p->website = malloc(strlen(modline) + 1); strcpy(p->website, modline); modline = strtok(NULL, ",\""); p->date = malloc(strlen(modline) + 1); strcpy(p->date, modline); modline = strtok(NULL, ",\""); p->cost = malloc(strlen(modline) + 1); strcpy(p->cost, modline); modline = strtok(NULL, ",\""); p->notes = malloc(strlen(modline) + 1); strcpy(p->notes, modline); /* remove unwanted newline when note exists */ len = strlen(p->notes) - 1; if (p->notes[len] == '\n') p->notes[len] = '\0'; printf("%s, %s, %s, %s, %s\n", p->product, p->website, p->date, p->cost, p->notes); free(bup); } void freepurchases(struct purchase *purchases, size_t count) { size_t i = 0; while (i != count) { free(purchases[i].product); free(purchases[i].website); free(purchases[i].date); free(purchases[i].cost); free(purchases[i].notes); i++; } } int main(int argc, char **argv) { FILE *file; struct purchase purchases[512]; /* max 512 entries for now */ char *line; size_t len; ssize_t read; int i; if (argc != 2) { printf("use: %s csvfile\n", argv[0]); } file = fopen(argv[1], "r"); if (!file) { fprintf(stderr, "unable to open csv file\n"); exit(EXIT_FAILURE); } line = NULL; len = 0; i = 0; while ((read = getline(&line, &len, file)) != -1) { parsepurchase(&purchases[i], line); i++; } freepurchases(purchases, i); fclose(file); free(line); return EXIT_SUCCESS; }