Eliminating the getopt disgrace.

This commit is contained in:
Christoph Lohmann
2013-06-14 20:20:47 +02:00
parent 75c97de593
commit 4d38f60685
28 changed files with 724 additions and 476 deletions

69
nl.c
View File

@@ -14,39 +14,50 @@ static const char *sep = "\t";
static long incr = 1;
static regex_t preg;
static void
usage(void)
{
eprintf("usage: %s [-b style] [-i increment] [-s sep] [FILE...]\n",
argv0);
exit(1);
}
int
main(int argc, char *argv[])
{
char c;
FILE *fp;
char *r;
while((c = getopt(argc, argv, "b:i:s:")) != -1)
switch(c) {
case 'b':
mode = optarg[0];
if(optarg[0] == 'p')
regcomp(&preg, &optarg[1], REG_NOSUB);
else if(!strchr("ant", optarg[0]) || optarg[1] != '\0')
eprintf("usage: %s [-b mode] [-i increment] [-s separator] [file...]\n", argv[0]);
break;
case 'i':
incr = estrtol(optarg, 0);
break;
case 's':
sep = optarg;
break;
default:
exit(2);
ARGBEGIN {
case 'b':
r = EARGF(usage());
mode = r[0];
if(r[0] == 'p') {
regcomp(&preg, &r[1], REG_NOSUB);
} else if(!strchr("ant", mode)) {
usage();
}
if(optind == argc)
break;
case 'i':
incr = estrtol(EARGF(usage()), 0);
break;
case 's':
sep = EARGF(usage());
break;
default:
usage();
} ARGEND;
if(argc == 0) {
nl(stdin);
else for(; optind < argc; optind++) {
if(!(fp = fopen(argv[optind], "r")))
eprintf("fopen %s:", argv[optind]);
} else for(; argc > 0; argc--, argv++) {
if(!(fp = fopen(argv[0], "r")))
eprintf("fopen %s:", argv[0]);
nl(fp);
fclose(fp);
}
return EXIT_SUCCESS;
return 0;
}
void
@@ -56,12 +67,16 @@ nl(FILE *fp)
long n = 0;
size_t size = 0;
while(afgets(&buf, &size, fp))
while(afgets(&buf, &size, fp)) {
if((mode == 'a')
|| (mode == 'p' && !regexec(&preg, buf, 0, NULL, 0))
|| (mode == 't' && buf[0] != '\n'))
|| (mode == 'p'
&& !regexec(&preg, buf, 0, NULL, 0))
|| (mode == 't' && buf[0] != '\n')) {
printf("%6ld%s%s", n += incr, sep, buf);
else
} else {
printf(" %s", buf);
}
}
free(buf);
}