From 3c529c1b9b1b5b886b3e2cd99dec6ff0c595833c Mon Sep 17 00:00:00 2001 From: Tibor Bizjak Date: Sat, 22 Jul 2023 15:07:45 +0200 Subject: [PATCH] added optional argument flag parsing --- .../04-find/04-find.c | 46 +++++++++++++++---- 1 file changed, 38 insertions(+), 8 deletions(-) diff --git a/k&r/04-funcs-and-prog-struct/04-find/04-find.c b/k&r/04-funcs-and-prog-struct/04-find/04-find.c index 462bc80..276d28b 100644 --- a/k&r/04-funcs-and-prog-struct/04-find/04-find.c +++ b/k&r/04-funcs-and-prog-struct/04-find/04-find.c @@ -5,21 +5,52 @@ int find(char *pattern); +#define ARG_FLAGS X('n', lineno) X('x', except) + /* find pattern given by first arg in lines and print them - * compile with 04-find-no-overflow.c or 04-find-opt.c */ + * takes optional flags + * -x : print all except matching + * -n : print line numbers */ int main(int argc, char *argv[]) { - /* verify arg is given */ - if (argc < 2) { - printf("error: excpected pattern\n"); + int i; + char c; + + /* declare flag variables */ +#define X(c, flag_var) int flag_var = 0; + ARG_FLAGS +#undef X + char **parg = argv; + /* parse flag arguments */ + for (i = 1; *++parg; ) { + if (**parg != '-' || !(*parg)[1]) { + argv[i++] = *parg; + continue; + } + while (c = *++parg[0]) + switch (c) { + #define X(C, flag_var) case C: flag_var = 1; break; + ARG_FLAGS + #undef X + default: + printf("error: illegal option -%c\n", c); + argc = 0; + break; + } + --argc; + } + + if (argc != 2) { + printf("usage: find "); + #define X(c, _) printf("[-%c] ", c); + ARG_FLAGS + #undef X + printf("pattern\n"); return -1; } char *pattern = argv[1]; - /* verify pattern */ - char c; - int i; for (i = 0; (c = pattern[i]) != '\0'; i++) if (c == '\n') { printf("error: newline in pattern\n"); @@ -27,6 +58,5 @@ int main(int argc, char *argv[]) } int found = find(pattern); - printf("found = %d\n", found); return found; }