From d8b7e45a5900f677fb6ef19a5eb51855071520aa Mon Sep 17 00:00:00 2001 From: Lieuwe Rooijakkers Date: Sun, 4 Aug 2024 15:08:07 +0200 Subject: toilet: use loop_args --- src/toilet.c | 60 ++++++++++++++++++++++++++---------------------------------- 1 file changed, 26 insertions(+), 34 deletions(-) diff --git a/src/toilet.c b/src/toilet.c index b1da9f1..d9c2556 100644 --- a/src/toilet.c +++ b/src/toilet.c @@ -9,13 +9,16 @@ #include #include -#include "util/versie.h" -#include "util/error.h" #include "util/debug.h" +#include "util/error.h" +#include "util/loop_args.h" #include "util/map.h" +#include "util/versie.h" #include "io/read_file.h" +int modeMap; + static void usage(FILE *f) { fprintf(f, "Gebruik: toilet [-nchV] [BESTAND]...\n" @@ -112,7 +115,7 @@ size_t get_count(enum MODE mode, struct filebuf *fb) { } } -static void process(char *fname, struct filebuf *fb, int modeMap) { +static void process(char *fname, struct filebuf *fb) { for (enum MODE mode = 1; mode <= M_BYTES; mode <<= 1) { if (mode & modeMap) { const size_t count = get_count(mode, fb); @@ -126,38 +129,17 @@ static void process(char *fname, struct filebuf *fb, int modeMap) { // TODO: be smarter, toilet doesn't have to read the whole file in memory (for // unmappable files) -int entry_toilet(int argc, char **argv) { - int modeMap = 0; - char **args = parse_options(argc, argv, &modeMap); - if (modeMap == 0) { - modeMap = INT_MAX; - } - - if (*args == NULL) { +static int handle(char *arg, bool isstdin) { + if (isstdin) { struct filebuf *fb = stream_to_filebuf(stdin, 0); if (fb == NULL) goto err_stdin; - - process("", fb, modeMap); - return 0; - } - - while (*args != NULL) { - struct filebuf *fb = NULL; - - if (!strcmp(*args, "-")) { - fb = stream_to_filebuf(stdin, 0); - if (fb == NULL) goto err_stdin; - *args = ""; // no filename when stdin - } else { - bool isdir = false; - fb = file_to_filebuf(*args, 0, &isdir); - if (isdir) goto err_isdir; - else if (fb == NULL) goto err_file; - } - - process(*args, fb, modeMap); - - args++; + process("", fb); + } else { + bool isdir = false; + struct filebuf *fb = file_to_filebuf(arg, 0, &isdir); + if (isdir) goto err_isdir; + else if (fb == NULL) goto err_file; + process(arg, fb); } return 0; @@ -171,6 +153,16 @@ err_file: return 1; err_isdir: - fprintf(stderr, "toilet: bestand '%s' is een mapje\n", *args); + fprintf(stderr, "toilet: bestand '%s' is een mapje\n", arg); return 1; } + +int entry_toilet(int argc, char **argv) { + modeMap = 0; + char **args = parse_options(argc, argv, &modeMap); + if (modeMap == 0) { + modeMap = INT_MAX; + } + + return loop_args(args, handle); +} -- cgit v1.2.3-70-g09d2