added optional argument flag parsing
parent
ff3df46f36
commit
3c529c1b9b
|
@ -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;
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue