sbase/strings.c

94 lines
1.5 KiB
C
Raw Normal View History

2013-08-14 09:41:55 +00:00
/* See LICENSE file for copyright and license details. */
#include <limits.h>
2013-08-14 09:41:55 +00:00
#include <stdio.h>
2015-02-17 13:46:48 +00:00
#include <stdlib.h>
#include "utf.h"
2013-08-14 09:41:55 +00:00
#include "util.h"
static char *format = "";
2015-02-17 13:46:48 +00:00
static void
strings(FILE *fp, const char *fname, size_t len)
2015-02-17 13:46:48 +00:00
{
Rune r, *rbuf;
size_t i, bread;
off_t off;
rbuf = ereallocarray(NULL, len, sizeof(*rbuf));
2015-02-17 13:46:48 +00:00
for (off = 0, i = 0; (bread = efgetrune(&r, fp, fname)); ) {
off += bread;
if (r == Runeerror)
continue;
if (!isprintrune(r)) {
if (i > len)
putchar('\n');
2015-02-17 13:46:48 +00:00
i = 0;
continue;
}
if (i < len) {
rbuf[i++] = r;
continue;
} else if (i > len) {
efputrune(&r, stdout, "<stdout>");
continue;
2015-02-17 13:46:48 +00:00
}
printf(format, (long)off - i);
for (i = 0; i < len; i++)
efputrune(rbuf + i, stdout, "<stdout>");
efputrune(&r, stdout, "<stdout>");
i++;
}
free(rbuf);
2015-02-17 13:46:48 +00:00
}
2013-08-14 09:41:55 +00:00
static void
usage(void)
{
eprintf("usage: %s [-a] [-n num] [-t format] [file ...]\n", argv0);
2013-08-14 09:41:55 +00:00
}
int
main(int argc, char *argv[])
{
FILE *fp;
size_t len = 4;
int ret = 0;
char f;
2013-08-14 09:41:55 +00:00
ARGBEGIN {
2015-02-17 13:39:17 +00:00
case 'a':
break;
2015-02-17 13:46:48 +00:00
case 'n':
len = estrtonum(EARGF(usage()), 1, LLONG_MAX);
break;
case 't':
format = estrdup("%8l#: ");
f = *EARGF(usage());
if (f == 'd' || f == 'o' || f == 'x')
format[3] = f;
else
usage();
2015-02-17 13:46:48 +00:00
break;
2013-08-14 09:41:55 +00:00
default:
usage();
} ARGEND;
if (!argc) {
2015-02-17 13:46:48 +00:00
strings(stdin, "<stdin>", len);
} else {
for (; *argv; argc--, argv++) {
if (!(fp = fopen(*argv, "r"))) {
weprintf("fopen %s:", *argv);
ret = 1;
continue;
}
strings(fp, *argv, len);
fclose(fp);
}
2013-08-14 09:41:55 +00:00
}
return ret;
2013-08-14 09:41:55 +00:00
}