diff options
Diffstat (limited to 'src/shared.c')
-rw-r--r-- | src/shared.c | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/shared.c b/src/shared.c new file mode 100644 index 0000000..ee3c2f1 --- /dev/null +++ b/src/shared.c @@ -0,0 +1,46 @@ +#include "shared.h" + +#include <errno.h> +#include <stdarg.h> +#include <stdlib.h> +#include <string.h> + +void error(const char* format, ...) { + va_list list; + va_start(list, format); + + vfprintf(stderr, format, list); + fprintf(stderr, "\n"); + exit(EXIT_FAILURE); +} + +FILE* get_file(const char* path, const char* type) { + FILE* file = fopen(path, type); + if (file == NULL) { + error("error: failed to open file %s: %s", path, strerror(errno)); + } + return file; +} + +long int get_number(const char* text) { + char* end; + long int n = strtol(text, &end, 10); + if (text == end) { + error("error: %s is not a valid number", text); + } + return n; +} + +bool streql(const char* a, const char* b) { + if (*a != *b) return false; + int n = 0; + while (true) { + if (*(a+n) != *(b+n)) return false; + if (*(a+n) == '\0') return true; + ++n; + } +} + +bool prefix(const char* pre, const char* str) { + return strncmp(pre, str, strlen(pre)) == 0; +} |