OS1/movies/csv_parser.c

85 lines
1.6 KiB
C
Raw Normal View History

#include "csv_parser.h"
struct node* parse_csv() {
FILE * file;
file = fopen("movies_sample_1.csv", "r");
// 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);
return head;
}
struct csv* parse_line(char* line) {
struct csv* mov = malloc(sizeof(struct csv));
char* sub = strtok(line, ",");
char* title = malloc(sizeof(char) *(strlen(sub) + 1));
strcpy(title,sub);
mov->title = title;
mov->year = atoi(strtok(NULL, ","));
sub = strtok(NULL, ",");
char* languages = malloc(sizeof(char) *(strlen(sub) + 1));
strcpy(languages, sub);
mov->languages = languages;
//printf("%s\n", csv->languages);
mov->rating = atof(strtok(NULL, ""));
return mov;
}
void print_movies(struct node* head) {
if(!head) {
printf("You 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, %s, %f\n", printer->title, printer->year, printer->languages, printer->rating);
}