summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLieuwe Rooijakkers <lieuwerooijakkers@gmail.com>2024-08-02 23:03:36 +0200
committerLieuwe Rooijakkers <lieuwerooijakkers@gmail.com>2024-08-02 23:04:16 +0200
commitf6bc3ed808a79ecab79fa10078775270db187e0c (patch)
tree81a5025375ee3753850c544dc26b943732e2e6fa
parentec605bf138a16e62d6398d0bf2a43d2fea2dbe74 (diff)
hoofd: use read_file.h
-rw-r--r--src/hoofd.c69
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;
}