sbase/strings.c

93 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 == 0) {
2015-02-17 13:46:48 +00:00
strings(stdin, "<stdin>", len);
} else {
for (; argc > 0; argc--, argv++) {
if (!(fp = fopen(argv[0], "r"))) {
weprintf("fopen %s:", argv[0]);
ret = 1;
continue;
}
2015-02-17 13:46:48 +00:00
strings(fp, argv[0], len);
fclose(fp);
}
2013-08-14 09:41:55 +00:00
}
return ret;
2013-08-14 09:41:55 +00:00
}