sbase/strings.c

68 lines
1.1 KiB
C
Raw Normal View History

2013-08-14 05:41:55 -04:00
/* See LICENSE file for copyright and license details. */
#include <ctype.h>
#include <limits.h>
2013-08-14 05:41:55 -04:00
#include <stdio.h>
2015-02-17 08:46:48 -05:00
#include <stdlib.h>
2013-08-14 05:41:55 -04:00
#include "util.h"
2015-02-17 08:46:48 -05:00
static void
strings(FILE *fp, const char *fname, int len)
{
unsigned char buf[BUFSIZ];
int c, i = 0;
off_t offset = 0;
do {
offset++;
if (isprint(c = getc(fp)))
buf[i++] = c;
if ((!isprint(c) && i >= len) || i == sizeof(buf) - 1) {
buf[i] = '\0';
printf("%8ld: %s\n", (long)offset - i - 1, buf);
i = 0;
}
} while (c != EOF);
if (ferror(fp))
eprintf("%s: read error:", fname);
}
2013-08-14 05:41:55 -04:00
static void
usage(void)
{
2015-02-17 08:46:48 -05:00
eprintf("usage: %s [-a] [-n len] [file ...]\n", argv0);
2013-08-14 05:41:55 -04:00
}
int
main(int argc, char *argv[])
{
FILE *fp;
int ret = 0;
2015-02-17 08:46:48 -05:00
int len = 4;
2013-08-14 05:41:55 -04:00
ARGBEGIN {
2015-02-17 08:39:17 -05:00
case 'a':
break;
2015-02-17 08:46:48 -05:00
case 'n':
len = estrtonum(EARGF(usage()), 1, INT_MAX);
break;
2013-08-14 05:41:55 -04:00
default:
usage();
} ARGEND;
if (argc == 0) {
2015-02-17 08:46:48 -05: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 08:46:48 -05:00
strings(fp, argv[0], len);
fclose(fp);
}
2013-08-14 05:41:55 -04:00
}
return ret;
2013-08-14 05:41:55 -04:00
}