In general, POSIX does not define /dev/std{in, out, err} because it does not want to depend on the dev-filesystem. For utilities, it thus introduced the '-'-keyword to denote standard input (and output in some cases) and the programs have to deal with it accordingly. Sadly, the design of many tools doesn't allow strict shell-redirections and many scripts don't even use this feature when possible. Thus, we made the decision to implement it consistently across all tools where it makes sense (namely those which read files). Along the way, I spotted some behavioural bugs in libutil/crypt.c and others where it was forgotten to fshut the files after use.
98 lines
1.7 KiB
C
98 lines
1.7 KiB
C
/* See LICENSE file for copyright and license details. */
|
|
#include <limits.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
#include "utf.h"
|
|
#include "util.h"
|
|
|
|
static char *format = "";
|
|
|
|
static void
|
|
strings(FILE *fp, const char *fname, size_t len)
|
|
{
|
|
Rune r, *rbuf;
|
|
size_t i, bread;
|
|
off_t off;
|
|
|
|
rbuf = ereallocarray(NULL, len, sizeof(*rbuf));
|
|
|
|
for (off = 0, i = 0; (bread = efgetrune(&r, fp, fname)); ) {
|
|
off += bread;
|
|
if (r == Runeerror)
|
|
continue;
|
|
if (!isprintrune(r)) {
|
|
if (i > len)
|
|
putchar('\n');
|
|
i = 0;
|
|
continue;
|
|
}
|
|
if (i < len) {
|
|
rbuf[i++] = r;
|
|
continue;
|
|
} else if (i > len) {
|
|
efputrune(&r, stdout, "<stdout>");
|
|
continue;
|
|
}
|
|
printf(format, (long)off - i);
|
|
for (i = 0; i < len; i++)
|
|
efputrune(rbuf + i, stdout, "<stdout>");
|
|
efputrune(&r, stdout, "<stdout>");
|
|
i++;
|
|
}
|
|
free(rbuf);
|
|
}
|
|
|
|
static void
|
|
usage(void)
|
|
{
|
|
eprintf("usage: %s [-a] [-n num] [-t format] [file ...]\n", argv0);
|
|
}
|
|
|
|
int
|
|
main(int argc, char *argv[])
|
|
{
|
|
FILE *fp;
|
|
size_t len = 4;
|
|
int ret = 0;
|
|
char f;
|
|
|
|
ARGBEGIN {
|
|
case 'a':
|
|
break;
|
|
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();
|
|
break;
|
|
default:
|
|
usage();
|
|
} ARGEND;
|
|
|
|
if (!argc) {
|
|
strings(stdin, "<stdin>", len);
|
|
} else {
|
|
for (; *argv; argc--, argv++) {
|
|
if ((*argv)[0] == '-' && !(*argv)[1]) {
|
|
*argv = "<stdin>";
|
|
fp = stdin;
|
|
} else if (!(fp = fopen(*argv, "r"))) {
|
|
weprintf("fopen %s:", *argv);
|
|
ret = 1;
|
|
continue;
|
|
}
|
|
strings(fp, *argv, len);
|
|
if (fp != stdin && fshut(fp, *argv))
|
|
ret = 1;
|
|
}
|
|
}
|
|
|
|
return !!(fshut(stdin, "<stdin>") + fshut(stdout, "<stdout>")) || ret;
|
|
}
|