-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaoc_common.h
72 lines (64 loc) · 1.84 KB
/
aoc_common.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// AOC 2021 solution in C
// @chadsy
// Copyright (C) 2021 Chad Royal
// MIT License http://opensource.org/licenses/MIT
//
// Common header for some macros and implementations.
#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#include <errno.h>
#define countof(x) (sizeof(x)/sizeof(x[0]))
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
typedef struct runargs_t {
FILE *input;
FILE *output;
bool run_first;
bool run_second;
} runargs;
static char *trim(char *str) {
char *p = str + (strlen(str) - 1);
while (isspace(*p)) {
*p-- = '\0';
}
return str;
}
static runargs parse_args(int argc, char **argv) {
runargs args;
args.run_first = true;
args.run_second = true;
args.input = stdin;
args.output = stdout;
for (int i = 1; i < argc; i++) {
// If this is a single char, then it should be 1 or 2 for first or second pass
if (strlen(argv[i]) == 1) {
if (*argv[i] == '1') {
args.run_first = true;
args.run_second = false;
}
else if (*argv[1] == '2') {
args.run_second = true;
args.run_first = false;
}
else {
fprintf(stderr, "error: unknown pass specifier '%c'; ignoring.\n", *argv[i]);
args.run_first = true;
args.run_second = true;
}
}
else {
// Otherise, this is the input filename
FILE *f = fopen(trim(argv[i]), "r");
if (f) {
args.input = f;
}
else {
fprintf(stderr, "error: cannot open '%s', %s; using stdin instead.\n", argv[i], strerror(errno));
args.input = stdin;
}
}
}
return args;
}