diff options
Diffstat (limited to 'src')
-rw-r--r-- | src/hoofd.c | 69 |
1 files changed, 51 insertions, 18 deletions
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 <getopt.h> #include <pwd.h> #include <stdlib.h> +#include <string.h> #include <sys/types.h> #include <unistd.h> + #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; } |