sbase/nl.c

83 lines
1.4 KiB
C
Raw Normal View History

2011-05-29 16:30:44 -04:00
/* See LICENSE file for copyright and license details. */
#include <limits.h>
2011-05-29 16:30:44 -04:00
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
2011-05-29 16:30:44 -04:00
#include "text.h"
#include "util.h"
static void nl(const char *, FILE *);
2011-05-29 16:30:44 -04:00
static char mode = 't';
static const char *sep = "\t";
static long incr = 1;
static regex_t preg;
2013-06-14 14:20:47 -04:00
static void
usage(void)
{
2014-12-04 08:49:07 -05:00
eprintf("usage: %s [-b type] [-i incr] [-s sep] [file]\n", argv0);
2013-06-14 14:20:47 -04:00
}
2011-05-29 16:30:44 -04:00
int
main(int argc, char *argv[])
{
FILE *fp;
2013-06-14 14:20:47 -04:00
char *r;
2011-05-29 16:30:44 -04:00
2013-06-14 14:20:47 -04:00
ARGBEGIN {
case 'b':
r = EARGF(usage());
mode = r[0];
if (r[0] == 'p')
2014-11-16 09:17:24 -05:00
eregcomp(&preg, &r[1], REG_NOSUB);
else if (!strchr("ant", mode))
2013-06-14 14:20:47 -04:00
usage();
break;
case 'i':
incr = estrtonum(EARGF(usage()), 0, LONG_MAX);
2013-06-14 14:20:47 -04:00
break;
case 's':
sep = EARGF(usage());
break;
default:
usage();
} ARGEND;
2014-12-04 07:04:41 -05:00
if (argc > 1)
usage();
if (argc == 0) {
nl("<stdin>", stdin);
2014-12-04 07:04:41 -05:00
} else {
if (!(fp = fopen(argv[0], "r")))
eprintf("fopen %s:", argv[0]);
nl(argv[0], fp);
2011-05-29 16:30:44 -04:00
fclose(fp);
}
2014-12-04 07:04:41 -05:00
return 0;
2011-05-29 16:30:44 -04:00
}
void
nl(const char *name, FILE *fp)
2011-05-29 16:30:44 -04:00
{
char *buf = NULL;
long n = 0;
size_t size = 0;
2014-11-18 15:49:30 -05:00
while (getline(&buf, &size, fp) != -1) {
if ((mode == 'a')
|| (mode == 'p' && !regexec(&preg, buf, 0, NULL, 0))
|| (mode == 't' && buf[0] != '\n'))
2011-05-29 16:30:44 -04:00
printf("%6ld%s%s", n += incr, sep, buf);
else
2011-05-29 16:30:44 -04:00
printf(" %s", buf);
2013-06-14 14:20:47 -04:00
}
2011-05-29 16:30:44 -04:00
free(buf);
if (ferror(fp))
eprintf("%s: read error:", name);
2011-05-29 16:30:44 -04:00
}