#include "csv_parser.h" struct node* parse_csv(char* name) { FILE * file; file = fopen(name, "r"); if(!file) { printf("Your File was Stolen by the Gremlins\n"); exit(66); } // Buffer File For chars char* buffer; size_t buff_size = 1000; size_t chars = -2; buffer = malloc(buff_size * sizeof(char)); // Deal with Top of CSV getline(&buffer, &buff_size, file); chars = getline(&buffer, &buff_size, file); struct node* head = appendv_node(NULL, parse_line(buffer)); chars = getline(&buffer, &buff_size, file); // Actually Store the CSV while(chars != -1) { appendv_node(head, parse_line(buffer)); chars = getline(&buffer, &buff_size, file); } // Free unecessary buffer files free(buffer); fclose(file); printf("Processed file %s and processed data for %d movies.\n\n", name, count_nodes(head)); return head; } struct csv* parse_line(char* line) { struct csv* mov = malloc(sizeof(struct csv)); // Deal with title char* sub = strtok(line, ","); 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, ","); 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; } void print_movies(struct node* head) { if(!head) { printf("Yo F'd up mate (print_movies)"); return; } struct node* node = head; while(1) { print_line(node->data); if(node->node) node = node->node; else return; } } void print_line(struct csv* printer) { 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; }