grep: ARGBEGIN

This commit is contained in:
Connor Lane Smith 2012-05-31 19:38:25 +01:00
parent 171ef71c74
commit c2c5ea9c60
1 changed files with 37 additions and 30 deletions

67
grep.c
View File

@ -11,6 +11,7 @@
enum { Match = 0, NoMatch = 1, Error = 2 }; enum { Match = 0, NoMatch = 1, Error = 2 };
static void grep(FILE *, const char *, regex_t *); static void grep(FILE *, const char *, regex_t *);
static void usage(void);
static bool vflag = false; static bool vflag = false;
static bool many; static bool many;
@ -21,46 +22,46 @@ int
main(int argc, char *argv[]) main(int argc, char *argv[])
{ {
char c; char c;
int n, flags = REG_NOSUB; int i, n, flags = REG_NOSUB;
regex_t preg; regex_t preg;
FILE *fp; FILE *fp;
while((c = getopt(argc, argv, "Ecilnqv")) != -1) ARGBEGIN {
switch(c) { case 'E':
case 'E': flags |= REG_EXTENDED;
flags |= REG_EXTENDED; break;
break; case 'c':
case 'c': case 'l':
case 'l': case 'n':
case 'n': case 'q':
case 'q': mode = c;
mode = c; break;
break; case 'i':
case 'i': flags |= REG_ICASE;
flags |= REG_ICASE; break;
break; case 'v':
case 'v': vflag = true;
vflag = true; break;
break; default:
default: usage();
exit(Error); } ARGEND;
}
if(optind == argc)
enprintf(Error, "usage: %s [-Ecilnqv] pattern [files...]\n", argv[0]);
if((n = regcomp(&preg, argv[optind++], flags)) != 0) { if(argc == 0)
usage(); /* no pattern */
if((n = regcomp(&preg, argv[0], flags)) != 0) {
char buf[BUFSIZ]; char buf[BUFSIZ];
regerror(n, &preg, buf, sizeof buf); regerror(n, &preg, buf, sizeof buf);
enprintf(Error, "invalid pattern: %s\n", buf); enprintf(Error, "invalid pattern: %s\n", buf);
} }
many = (argc > optind+1); many = (argc > 1);
if(optind == argc) if(argc == 1)
grep(stdin, "<stdin>", &preg); grep(stdin, "<stdin>", &preg);
else for(; optind < argc; optind++) { else for(i = 1; i < argc; i++) {
if(!(fp = fopen(argv[optind], "r"))) if(!(fp = fopen(argv[i], "r")))
enprintf(Error, "fopen %s:", argv[optind]); enprintf(Error, "fopen %s:", argv[i]);
grep(fp, argv[optind], &preg); grep(fp, argv[i], &preg);
fclose(fp); fclose(fp);
} }
return match ? Match : NoMatch; return match ? Match : NoMatch;
@ -104,3 +105,9 @@ end:
enprintf(Error, "%s: read error:", str); enprintf(Error, "%s: read error:", str);
free(buf); free(buf);
} }
void
usage(void)
{
enprintf(Error, "usage: %s [-Ecilnqv] pattern [files...]\n", argv0);
}