main.c (1356B)
1#include "aoc.h" 2#include "util.h" 3#include <err.h> 4#include <stdio.h> 5 6struct aoc aoc; 7 8int 9main(int argc, const char **argv) 10{ 11 const char *envvar; 12 FILE *f; 13 14 if (argc <= 1) { 15 fprintf(stderr, "Usage: main PART [ARG]..\n"); 16 exit(0); 17 } 18 19 aoc.part = atoi(argv[1]); 20 aoc.argc = argc - 2; 21 aoc.argv = &argv[2]; 22 23 envvar = getenv("AOC_DEBUG"); 24 aoc.debug = envvar ? atoi(envvar) : 0; 25 26 /* parse user input */ 27 aoc.inputfile = getenv("AOC_INPUT"); 28 if (!aoc.inputfile) aoc.inputfile = "input"; 29 else aoc_debug("Using input file: '%s'\n", aoc.inputfile); 30 31 /* read input file */ 32 if (!(f = fopen(aoc.inputfile, "r"))) 33 err(1, "fopen %s", aoc.inputfile); 34 readall(f, (void**) &aoc.input, &aoc.input_size); 35 fclose(f); 36 37 /* add null terminator */ 38 aoc.input = realloc(aoc.input, aoc.input_size + 1); 39 if (!aoc.input) err(1, "realloc"); 40 aoc.input[aoc.input_size] = '\0'; 41 42 /* call solution */ 43 aoc.answer = NULL; 44 aoc.solution = NULL; 45 if (aoc.part == 1) part1(); 46 else if (aoc.part == 2) part2(); 47 else errx(1, "Invalid part number"); 48 49 /* check answer if given */ 50 if (aoc.answer) { 51 printf("%s\n", aoc.answer); 52 if (!strcmp(aoc.inputfile, "input")) { 53 if (aoc.solution && strcmp(aoc.answer, aoc.solution)) 54 errx(1, "Incorrect solution!"); 55 else if (!aoc.solution) 56 errx(1, "Solution missing!"); 57 } 58 } 59 60 free(aoc.answer); 61 free(aoc.input); 62}