diff options
| author | Jakob Kaivo <jkk@ung.org> | 2022-04-20 21:42:58 -0400 |
|---|---|---|
| committer | Jakob Kaivo <jkk@ung.org> | 2022-04-20 21:42:58 -0400 |
| commit | 9bc84a0be431ff146d74df7d97a9ce94423ab558 (patch) | |
| tree | 13199220bb6d8d04c8a7f6c01c4b49d30f0e3566 | |
| parent | 85647411a613be53eceeb4807927da06426369b5 (diff) | |
start working on -l and -c
| -rw-r--r-- | grep.c | 36 |
1 files changed, 25 insertions, 11 deletions
@@ -25,6 +25,7 @@ #define _POSIX_C_SOURCE 200809L #include <errno.h> +#include <inttypes.h> #include <locale.h> #include <regex.h> #include <stdio.h> @@ -38,12 +39,9 @@ struct grep_list { regex_t re; }; -#define NORMAL 0 -#define COUNT 1 -#define LIST 2 -#define QUIET 3 +enum { NORMAL, COUNT, LIST, QUIET } grep_display = NORMAL; +static int grep_filenames = 0; -#define IGNORECASE 1 << 0 #define LINENUMBERS 1 << 1 #define SUPPRESS 1 << 2 #define INVERT 1 << 3 @@ -68,7 +66,7 @@ static int grep_match(struct grep_list *head, const char *buf) return 0; } -static int grep(struct grep_list *head, const char *path, int flags) +static uintmax_t grep(struct grep_list *head, const char *path, int flags) { (void)flags; @@ -83,7 +81,7 @@ static int grep(struct grep_list *head, const char *path, int flags) } } - int found = 0; + uintmax_t found = 0; char *buf = NULL; size_t len = 0; while (getline(&buf, &len, f) != -1) { @@ -92,13 +90,26 @@ static int grep(struct grep_list *head, const char *path, int flags) *nl = '\0'; } if (grep_match(head, buf)) { - printf("%s\n", buf); + if (grep_display == NORMAL) { + printf("%s\n", buf); + } found++; } } fclose(f); + if (grep_display == COUNT) { + if (grep_filenames) { + printf("%s:", path); + } + printf("%ju\n", found); + } + + if (grep_display == LIST && found > 0) { + printf("%s\n", path); + } + return found; } @@ -169,7 +180,7 @@ int main(int argc, char *argv[]) break; case 'c': - //display = COUNT; + grep_display = COUNT; break; case 'e': @@ -185,7 +196,7 @@ int main(int argc, char *argv[]) break; case 'l': - //display = LIST; + grep_display = LIST; break; case 'n': @@ -236,8 +247,11 @@ int main(int argc, char *argv[]) return 2; } } + + printf("argc %d, optind %d\n", argc, optind); + grep_filenames = (argc - optind < 2); - int found = 0; + uintmax_t found = 0; do { found += grep(head, argv[optind++], flags); } while (optind < argc); |
