#include #include #include #include "ratings.h" // Function to load all ratings into a list int load_ratings(RatingInfo **ratings) { const char* filename = "imdb/title.ratings.tsv"; FILE *file = fopen(filename, "r"); if (file == NULL) { fprintf(stderr, "Error opening file.\n"); return -1; } // Skip the header line char line[256]; fgets(line, sizeof(line), file); // Dynamically allocate memory for the ratings list int capacity = 10; int count = 0; *ratings = (RatingInfo *)malloc(capacity * sizeof(RatingInfo)); if (*ratings == NULL) { fprintf(stderr, "Memory allocation failed.\n"); fclose(file); return -1; } // Read each line and store the ratings while (fgets(line, sizeof(line), file)) { // Check if we need to resize the array if (count >= capacity) { capacity *= 2; // Double the capacity *ratings = (RatingInfo *)realloc(*ratings, capacity * sizeof(RatingInfo)); if (*ratings == NULL) { fprintf(stderr, "Memory allocation failed during resizing.\n"); fclose(file); return -1; } } // Parse the line and store the data if (sscanf(line, "%19s\t%f\t%d", (*ratings)[count].tconst, &(*ratings)[count].averageRating, &(*ratings)[count].numVotes) == 3) { count++; } } fclose(file); return count; // Return the number of ratings loaded } // Function to search for a rating by tconst RatingInfo *get_rating_by_tconst(const char *tconst, RatingInfo *ratings, int* ratings_count) { static int i = 0; char t[10] = "\0"; strcpy(t, ratings[i].tconst); if (strlen(t) == 0 || strlen(ratings[i].tconst) == 0) return NULL; while (strcmp(ratings[i].tconst, t) < 0) { if (strlen(t) == 0 || strlen(ratings[i].tconst) == 0) return NULL; if (i == (*ratings_count)-1) return NULL; strcpy(t, ratings[++i].tconst); } if (strcmp(ratings[i].tconst, t) > 0) return NULL; return &ratings[i++]; for (; i < *ratings_count; i++) { if (strcmp(ratings[i].tconst, tconst) == 0) { ratings[i] = ratings[((*ratings_count)--)]; strcpy(t, tconst); return &ratings[i]; // Return a pointer to the matching rating } if (strcmp(ratings[i].tconst, tconst) > 0) return NULL; } return NULL; // Return NULL if not found } int testRat() { RatingInfo *ratings = NULL; // Load the ratings from the file int ratings_count = load_ratings(&ratings); for (int i = 0; i < 10; i++) printf("%s %3d %f %s\n", ratings[i].tconst, i, ratings[i].averageRating, ratings[i].tconst); exit(1); if (ratings_count < 0) { fprintf(stderr, "Failed to load ratings.\n"); return 1; } // Example tconst to search for const char *tconst = "tt0000001"; // Replace with the tconst you want to search // Search for the rating RatingInfo *rating = get_rating_by_tconst(tconst, ratings, &ratings_count); if (rating != NULL) { printf("Ratings for %s:\n", rating->tconst); printf("Average Rating: %.1f\n", rating->averageRating); printf("Number of Votes: %d\n", rating->numVotes); } else { printf("No ratings found for %s\n", tconst); } // Free the allocated memory free(ratings); return 0; }