Finish CSV Parsing Logic

This commit is contained in:
stitchy 2023-10-13 00:55:11 -07:00
parent 367b12484f
commit 14a6bd5df5
Signed by: stitchy
SSH key fingerprint: SHA256:yz2SoxdnY67tfY5Jzb0f2v8f5W3o/IF359kbcquWip8
2 changed files with 47 additions and 9 deletions

View file

@ -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;
}

View file

@ -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