From f6bc3ed808a79ecab79fa10078775270db187e0c Mon Sep 17 00:00:00 2001 From: Lieuwe Rooijakkers Date: Fri, 2 Aug 2024 23:03:36 +0200 Subject: hoofd: use read_file.h --- src/hoofd.c | 69 +++++++++++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 51 insertions(+), 18 deletions(-) (limited to 'src/hoofd.c') diff --git a/src/hoofd.c b/src/hoofd.c index f043f2b..3474b0b 100644 --- a/src/hoofd.c +++ b/src/hoofd.c @@ -1,12 +1,15 @@ #include #include #include +#include #include #include + #include "util/versie.h" #include "util/error.h" #include "util/debug.h" -#include "util/map.h" + +#include "io/read_file.h" static void usage(FILE *f) { fprintf(f, @@ -53,34 +56,64 @@ static char** parse_options(int argc, char **argv, int *n, int *c) { return argv + optind; } +// TODO: be smarter, hoofd doesn't have to read the whole file in memory (for +// unmappable files) + +static void process(struct filebuf *fb, int n, int c) { + size_t i; + for (i = 0; i < fb->sz && (n > 0 || n == -1) && (c > 0 || c == -1); i++) { + if (fb->buf[i] == '\n') { + if (n != -1) n--; + } + if (c != -1) c--; + } + fwrite(fb->buf, 1, i, stdout); + + free_filebuf(fb); +} + int entry_hoofd(int argc, char **argv) { int n = 10; int c = -1; char **args = parse_options(argc, argv, &n, &c); + if (*args == NULL) { + struct filebuf *fb = stream_to_filebuf(stdin, 0); + if (fb == NULL) goto err_stdin; + + process(fb, n, c); + return 0; + } + while (*args != NULL) { - bool isdir; - struct map *map = open_map(*args, &isdir); - if (isdir) { - fprintf(stderr, "hoofd: %s: is een mapje\n", *args); - goto next; - } else if (map == NULL) { - fprintf(stderr, "hoofd: fout bij lezen bestand"); - return 1; - } + struct filebuf *fb = NULL; - size_t i; - for (i = 0; i < (size_t)map->sb.st_size && (n > 0 || n == -1) && (c > 0 || c == -1); i++) { - if (map->addr[i] == '\n') { - if (n != -1) n--; - } - if (c != -1) c--; + if (!strcmp(*args, "-")) { + fb = stream_to_filebuf(stdin, 0); + if (fb == NULL) goto err_stdin; + } else { + bool isdir = false; + fb = file_to_filebuf(*args, 0, &isdir); + if (isdir) goto err_isdir; + else if (fb == NULL) goto err_file; } - fwrite(map->addr, 1, i, stdout); -next: + process(fb, n, c); + args++; } return 0; + +err_stdin: + fprintf(stderr, "hoofd: fout bij lezen van standaard invoer\n"); + return 1; + +err_file: + fprintf(stderr, "hoofd: fout bij lezen van bestand\n"); + return 1; + +err_isdir: + fprintf(stderr, "hoofd: bestand '%s' is een mapje\n", *args); + return 1; } -- cgit v1.2.3-70-g09d2