#include #include #include #include "parsers/json.h" typedef enum { music = 0, art = 1, blog = 2, } MediaType; MediaType read_media_type(char *name) { char *type_names[] = {"music", "art", "blog"}; for (int i = 0; i < sizeof(type_names) / sizeof(char*); i++) { if (strcmp(name, type_names[i]) == 0) return i; } return -1; } void print_help() { printf("usage: compile <-t media_type> <-i input_file> [output_file]\n"); printf("valid media types: music, art, blog\n"); printf("if output_file is not specified, the output will be written to stdout.\n"); } int main(int argc, char **argv) { if (argc <= 1) { print_help(); return 0; } MediaType media_type = -1; FILE *input_file = NULL; size_t optind = 0; for (optind = 1; optind < argc && argv[optind][0] == '-'; optind++) { switch (argv[optind][1]) { case 't': media_type = read_media_type(argv[++optind]); if (media_type < 0) { fprintf(stderr, "media type `%s` is not implemented!\n\n", argv[optind]); print_help(); exit(EXIT_FAILURE); } break; case 'i': if (optind++ >= argc) { fprintf(stderr, "-i was passed, but no file path was given!\n\n"); exit(EXIT_FAILURE); } input_file = fopen(argv[optind], "r"); if (input_file == NULL) { fprintf(stderr, "failed to open file %s!\n\n", argv[optind]); exit(EXIT_FAILURE); } break; default: print_help(); exit(EXIT_FAILURE); } } if (media_type < 0) { fprintf(stderr, "media type not provided!\n\n"); print_help(); exit(EXIT_FAILURE); } if (input_file == NULL) { fprintf(stderr, "input file not provided!\n\n"); print_help(); exit(EXIT_FAILURE); } // get length of file fseek(input_file, -sizeof(char), SEEK_END); size_t length = ftell(input_file); fseek(input_file, 0, SEEK_SET); // read file to buffer char buf[length + 1]; fread(buf, 1, length, input_file); buf[length] = '\0'; size_t offset = 0; JsonObject *json = json_parse(buf, &offset); if (json == NULL) { fprintf(stderr, "failed to parse input file!\n"); exit(EXIT_FAILURE); } printf("title: %s\n", (char*)json_get(json, "title")); printf("type: %s\n", (char*)json_get(json, "type")); printf("year: %.0f\n", *(float*)json_get(json, "year")); printf("artwork: %s\n", (char*)json_get(json, "artwork")); printf("buylink: %s\n", (char*)json_get(json, "buylink")); JsonArrayItem *links = json_get(json, "links"); size_t i = 0; while (links != NULL) { JsonObject *link = links->value; printf("links.%zu.title: %s\n", i, (char*)json_get(link, "title")); printf("links.%zu.url: %s\n", i, (char*)json_get(link, "url")); links = links->next; i++; } return 0; }