#include #include #include #include #ifdef __linux__ #include #endif #include "input.h" char *get_input(const char *path) { FILE *fp = NULL; fp = fopen(path, "r"); if (fp == NULL) { printf("Failed to open %s. Exiting.\n", path); exit(1); } fseek(fp, 0, SEEK_END); size_t fsz = ftell(fp); rewind(fp); char* buf = NULL; buf = malloc(fsz + 1); if (buf == NULL) { printf("Failed to malloc buf. Exiting.\n"); exit(1); } fread(buf, 1, fsz, fp); buf[fsz] = '\0'; fclose(fp); return buf; } char **get_lines(const char *path, size_t *lsz) { char **lines = NULL; char *delim = "\n"; char *s = get_input(path), *t = strtok(s, delim); size_t n = 0; while (t != NULL) { lines = realloc(lines, sizeof(char *) * ++n); if (lines == NULL) { printf("Failed to realloc lines buffer. Exiting.\n"); exit(1); } lines[n - 1] = t; t = strtok(NULL, delim); } *lsz = n; return lines; } int *get_ints(const char *path, size_t *sz) { char **lines = get_lines(path, sz); int *i = malloc(sizeof(int) * *sz); for (size_t idx = 0; idx < *sz; idx++) { int n; const char *errstr; n = strtonum(lines[idx], INT_MIN, INT_MAX, &errstr); if (errstr) { printf("Failed to convert %s to int. Exiting.\n", lines[idx]); exit(1); } i[idx] = n; } del_lines(lines); return i; } void del_lines(char **lines) { free(lines[0]); free(lines); }