From 7639fa582728adfc6d3fa51852fffc9ad519b526 Mon Sep 17 00:00:00 2001 From: Lieuwe Rooijakkers Date: Sun, 21 Jul 2024 18:18:50 +0200 Subject: tak: betere afhandeling als projecteren niet lukt --- src/tak.c | 74 +++++++++++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 51 insertions(+), 23 deletions(-) (limited to 'src/tak.c') diff --git a/src/tak.c b/src/tak.c index ead1038..d92123a 100644 --- a/src/tak.c +++ b/src/tak.c @@ -74,13 +74,13 @@ static void process(struct state state) { return NULL; \ } -static char *read_stdin(size_t *sz) { +static char *read_stream(FILE *stream, size_t *sz) { *sz = 0; size_t cap = 4096; char *res = malloc(cap); CHECK_OOM(res); - while (!feof(stdin)) { + while (!feof(stream)) { if (cap-*sz == 0) { cap *= 2; res = realloc(res, cap); @@ -88,10 +88,10 @@ static char *read_stdin(size_t *sz) { } const size_t amount = cap-*sz; - const size_t n = fread(res+*sz, 1, amount, stdin); + const size_t n = fread(res+*sz, 1, amount, stream); *sz += n; - if (n != amount && !feof(stdin)) { + if (n != amount && !feof(stream)) { fprintf(stderr, "tak: fout tijdens lezen van standaard invoer.\n"); free(res); return NULL; @@ -101,32 +101,60 @@ static char *read_stdin(size_t *sz) { return res; } +int handleStream(FILE *stream) { + size_t sz = 0; + char *data = read_stream(stream, &sz); + if (data == NULL) { + return 1; + } + + struct state state = { .buf = data, .sz = sz }; + process(state); + + free(data); + return 0; +} + +int handleFile(char *fname) { + struct map *map = open_map(fname); + if (map == NULL) { + return 1; + } + + struct state state = { .buf = map->addr, .sz = map->sb.st_size }; + process(state); + + close_map(map); + + return 0; +} + int entry_tak(int argc, char **argv) { char **args = parse_options(argc, argv); - if (*args == NULL) { - size_t sz = 0; - char *data = read_stdin(&sz); - if (data == NULL) { - return 1; - } - struct state state = { .buf = data, .sz = sz }; - process(state); + if (*args == NULL) { + handleStream(stdin); + return 0; + } - free(data); - } else { - while (*args != NULL) { - struct map *map = open_map(*args); - if (map == NULL) { - return 1; - } + while (*args != NULL) { + if (!strcmp(*args, "-")) { + handleStream(stdin); + goto next; + } - struct state state = { .buf = map->addr, .sz = map->sb.st_size }; - process(state); + if (!handleFile(*args)) { + goto next; + } - close_map(map); - args++; + FILE *stream = fopen(*args, "rb"); + if (handleStream(stream)) { + return 1; } + fclose(stream); + +next: + args++; } return 0; -- cgit v1.2.3-70-g09d2