diff options
author | Lieuwe Rooijakkers <lieuwerooijakkers@gmail.com> | 2024-08-06 19:34:00 +0200 |
---|---|---|
committer | Lieuwe Rooijakkers <lieuwerooijakkers@gmail.com> | 2024-08-06 19:41:07 +0200 |
commit | 3145dd8188c4c807b5cfb6cd16a3e8088544f96e (patch) | |
tree | 02224110f85c052bd3b4cbeaa6a80f10c93d54e7 /src | |
parent | 37669147781468a0908c1240b26055898ca1e431 (diff) |
simple grijp with fixed strings only
Diffstat (limited to 'src')
-rw-r--r-- | src/grijp.c | 104 |
1 files changed, 104 insertions, 0 deletions
diff --git a/src/grijp.c b/src/grijp.c new file mode 100644 index 0000000..0c406f4 --- /dev/null +++ b/src/grijp.c @@ -0,0 +1,104 @@ +#include <assert.h> +#include <errno.h> +#include <getopt.h> +#include <pwd.h> +#include <stdlib.h> +#include <string.h> +#include <sys/types.h> +#include <unistd.h> + +#include "util/debug.h" +#include "util/error.h" +#include "util/loop_args.h" +#include "util/versie.h" + +#include "io/read_file.h" + +char *gpats; + +static void usage(FILE *f) { + fprintf(f, + "Gebruik: grijp [-hV] [PATRONEN] [BESTAND]...\n" + "\n" + "TODO\n" + "\n" + " -h Toon deze hulptekst\n" + " -V Toon versienummer\n"); +} + +// Returns pointer to argument array containing patterns and then the file names +static char** parse_options(int argc, char **argv) { + int opt; + while ((opt = getopt(argc, argv, "hV")) != -1) { + switch (opt) { + case 'h': + usage(stdout); + exit(0); + + case 'V': + drukkedoos_print_versie(stdout); + exit(0); + + case '?': + fprintf(stderr, "grijp: Ongeldige optie: -%c\n", optopt); + usage(stderr); + exit(1); + } + } + + return argv + optind; +} + +static int process(char *fname, bool isstdin) { + FILE *stream = isstdin ? stdin : fopen(fname, "rb"); + + char **patterns; + size_t npat = 0; + { + size_t cappat = 1 << 4; + patterns = calloc(sizeof(char*), cappat); + + char *s = gpats; + char *pat = NULL; + while ((pat = strtok(s, "\n")) != NULL) { + s = NULL; + + if (npat == cappat) { + cappat *= 2; + patterns = realloc(patterns, sizeof(char*)*cappat); + } + patterns[npat] = strdup(pat); + npat++; + } + } + + char *line = NULL; + size_t linen = 0; + + ssize_t nread = 0; + while ((errno = 0, nread = getline(&line, &linen, stream)) != -1) { + for (size_t i = 0; i < npat; i++) { + char *pat = patterns[i]; + if (strstr(line, pat) == NULL) continue; + printf("%s", line); + } + } + free(line); + + for (size_t i = 0; i < npat; i++) free(patterns[i]); + free(patterns); + + return 0; +} + +int entry_grijp(int argc, char **argv) { + char **args = parse_options(argc, argv); + if (*args == NULL) { + fprintf(stderr, "grijp: geen patroon gegeven\n"); + return 1; + } + + gpats = *args; + args++; + return loop_args(args, process); +} |