Respect exit status in nl(1) + some stylistic changes

This commit is contained in:
sin 2014-12-04 12:00:19 +00:00
parent 95c9b4b255
commit 86c88d8b3a

28
nl.c
View File

@ -8,7 +8,7 @@
#include "text.h" #include "text.h"
#include "util.h" #include "util.h"
static void nl(FILE *); static void nl(const char *, FILE *);
static char mode = 't'; static char mode = 't';
static const char *sep = "\t"; static const char *sep = "\t";
@ -27,16 +27,16 @@ main(int argc, char *argv[])
{ {
FILE *fp; FILE *fp;
char *r; char *r;
int ret = 0;
ARGBEGIN { ARGBEGIN {
case 'b': case 'b':
r = EARGF(usage()); r = EARGF(usage());
mode = r[0]; mode = r[0];
if (r[0] == 'p') { if (r[0] == 'p')
eregcomp(&preg, &r[1], REG_NOSUB); eregcomp(&preg, &r[1], REG_NOSUB);
} else if (!strchr("ant", mode)) { else if (!strchr("ant", mode))
usage(); usage();
}
break; break;
case 'i': case 'i':
incr = estrtol(EARGF(usage()), 0); incr = estrtol(EARGF(usage()), 0);
@ -49,21 +49,21 @@ main(int argc, char *argv[])
} ARGEND; } ARGEND;
if (argc == 0) { if (argc == 0) {
nl(stdin); nl("<stdin>", stdin);
} else for (; argc > 0; argc--, argv++) { } else for (; argc > 0; argc--, argv++) {
if (!(fp = fopen(argv[0], "r"))) { if (!(fp = fopen(argv[0], "r"))) {
weprintf("fopen %s:", argv[0]); weprintf("fopen %s:", argv[0]);
ret = 1;
continue; continue;
} }
nl(fp); nl(argv[0], fp);
fclose(fp); fclose(fp);
} }
return ret;
return 0;
} }
void void
nl(FILE *fp) nl(const char *name, FILE *fp)
{ {
char *buf = NULL; char *buf = NULL;
long n = 0; long n = 0;
@ -71,13 +71,13 @@ nl(FILE *fp)
while (getline(&buf, &size, fp) != -1) { while (getline(&buf, &size, fp) != -1) {
if ((mode == 'a') if ((mode == 'a')
|| (mode == 'p' || (mode == 'p' && !regexec(&preg, buf, 0, NULL, 0))
&& !regexec(&preg, buf, 0, NULL, 0)) || (mode == 't' && buf[0] != '\n'))
|| (mode == 't' && buf[0] != '\n')) {
printf("%6ld%s%s", n += incr, sep, buf); printf("%6ld%s%s", n += incr, sep, buf);
} else { else
printf(" %s", buf); printf(" %s", buf);
}
} }
free(buf); free(buf);
if (ferror(fp))
eprintf("%s: read error:", name);
} }