[hackers] [sbase] grep: ARGBEGIN || Connor Lane Smith
changeset: 142:a5f091c1c5f8
tag: tip
user: Connor Lane Smith <cls_AT_lubutu.com>
date: Thu May 31 19:38:25 2012 +0100
files: grep.c
description:
grep: ARGBEGIN
diff -r b98778a933b8 -r a5f091c1c5f8 grep.c
--- a/grep.c Thu May 31 19:38:18 2012 +0100
+++ b/grep.c Thu May 31 19:38:25 2012 +0100
_AT_@ -11,6 +11,7 @@
enum { Match = 0, NoMatch = 1, Error = 2 };
static void grep(FILE *, const char *, regex_t *);
+static void usage(void);
static bool vflag = false;
static bool many;
_AT_@ -21,46 +22,46 @@
main(int argc, char *argv[])
{
char c;
- int n, flags = REG_NOSUB;
+ int i, n, flags = REG_NOSUB;
regex_t preg;
FILE *fp;
- while((c = getopt(argc, argv, "Ecilnqv")) != -1)
- switch(c) {
- case 'E':
- flags |= REG_EXTENDED;
- break;
- case 'c':
- case 'l':
- case 'n':
- case 'q':
- mode = c;
- break;
- case 'i':
- flags |= REG_ICASE;
- break;
- case 'v':
- vflag = true;
- break;
- default:
- exit(Error);
- }
- if(optind == argc)
- enprintf(Error, "usage: %s [-Ecilnqv] pattern [files...]\n", argv[0]);
+ ARGBEGIN {
+ case 'E':
+ flags |= REG_EXTENDED;
+ break;
+ case 'c':
+ case 'l':
+ case 'n':
+ case 'q':
+ mode = c;
+ break;
+ case 'i':
+ flags |= REG_ICASE;
+ break;
+ case 'v':
+ vflag = true;
+ break;
+ default:
+ usage();
+ } ARGEND;
- 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];
regerror(n, &preg, buf, sizeof buf);
enprintf(Error, "invalid pattern: %s\n", buf);
}
- many = (argc > optind+1);
- if(optind == argc)
+ many = (argc > 1);
+ if(argc == 1)
grep(stdin, "<stdin>", &preg);
- else for(; optind < argc; optind++) {
- if(!(fp = fopen(argv[optind], "r")))
- enprintf(Error, "fopen %s:", argv[optind]);
- grep(fp, argv[optind], &preg);
+ else for(i = 1; i < argc; i++) {
+ if(!(fp = fopen(argv[i], "r")))
+ enprintf(Error, "fopen %s:", argv[i]);
+ grep(fp, argv[i], &preg);
fclose(fp);
}
return match ? Match : NoMatch;
_AT_@ -104,3 +105,9 @@
enprintf(Error, "%s: read error:", str);
free(buf);
}
+
+void
+usage(void)
+{
+ enprintf(Error, "usage: %s [-Ecilnqv] pattern [files...]\n", argv0);
+}
Received on Thu May 31 2012 - 20:38:49 CEST
This archive was generated by hypermail 2.3.0
: Thu May 31 2012 - 20:48:08 CEST