From 14a6bd5df5a12e0f1ce5884547b3af1e7464423c Mon Sep 17 00:00:00 2001 From: stitchy Date: Fri, 13 Oct 2023 00:55:11 -0700 Subject: [PATCH] Finish CSV Parsing Logic --- movies/csv_parser.c | 52 ++++++++++++++++++++++++++++++++++++++------- movies/csv_parser.h | 4 +++- 2 files changed, 47 insertions(+), 9 deletions(-) diff --git a/movies/csv_parser.c b/movies/csv_parser.c index cdb990f..48a0c77 100644 --- a/movies/csv_parser.c +++ b/movies/csv_parser.c @@ -39,21 +39,40 @@ struct csv* parse_line(char* line) { struct csv* mov = malloc(sizeof(struct csv)); + // Deal with title char* sub = strtok(line, ","); - char* title = malloc(sizeof(char) *(strlen(sub) + 1)); - strcpy(title,sub); - mov->title = title; + mov->title = malloc(sizeof(char) *(strlen(sub) + 1)); + strcpy(mov->title, sub); mov->year = atoi(strtok(NULL, ",")); + // Allocate number of languages and save string sub = strtok(NULL, ","); - char* languages = malloc(sizeof(char) *(strlen(sub) + 1)); - strcpy(languages, sub); - mov->languages = languages; - //printf("%s\n", csv->languages); + mov->numlang = 1 + count_char(sub, ';'); + mov->languages = malloc(mov->numlang * sizeof(char*)); + + char* lang = malloc(sizeof(char) * (strlen(sub) + 1)); + strcpy(lang, sub); mov->rating = atof(strtok(NULL, "")); + + // Finish parsing Languages + for(int i = 0; i < mov->numlang; i++) { + + if(!i) + sub = strtok( (lang+1), ";"); + else + sub = strtok(NULL, ";"); + + mov->languages[i] = malloc(sizeof(char) * (strlen(sub) + 1)); + strcpy(mov->languages[i], sub); + + } + + // Remove icky char from end of last string + mov->languages[mov->numlang - 1][strlen(mov->languages[mov->numlang - 1]) - 1] = '\0'; + return mov; } @@ -79,6 +98,23 @@ void print_movies(struct node* head) { void print_line(struct csv* printer) { - printf("%s, %i, %s, %f\n", printer->title, printer->year, printer->languages, printer->rating); + printf("%s, %i, ", printer->title, printer->year); + for(int i = 0; i < printer->numlang; i++) { + printf("%s:", printer->languages[i]); + } + printf(", %f\n", printer->rating); } + +int count_char(char* text, char cha) { + + int length = strlen(text); + int num = 0; + + for(int i = 0; i < length; i++) { + if(text[i] == cha) + num++; + } + + return num; +} diff --git a/movies/csv_parser.h b/movies/csv_parser.h index 679ddfb..db9bc47 100644 --- a/movies/csv_parser.h +++ b/movies/csv_parser.h @@ -12,7 +12,7 @@ struct csv { char* title; int year; int numlang; - char* languages; + char** languages; float rating; struct node* node; }; @@ -25,4 +25,6 @@ void print_movies(struct node*); void print_line(struct csv*); +int count_char(char*, char); + #endif