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.
105 lines
1.8 KiB
C
105 lines
1.8 KiB
C
/* See LICENSE file for copyright and license details. */
|
|
#include "utf.h"
|
|
#include "util.h"
|
|
|
|
static int lflag = 0;
|
|
static int wflag = 0;
|
|
static char cmode = 0;
|
|
static size_t tc = 0, tl = 0, tw = 0;
|
|
|
|
static void
|
|
output(const char *str, size_t nc, size_t nl, size_t nw)
|
|
{
|
|
int noflags = !cmode && !lflag && !wflag;
|
|
int first = 1;
|
|
|
|
if (lflag || noflags)
|
|
printf("%*.1zu", first ? (first = 0) : 7, nl);
|
|
if (wflag || noflags)
|
|
printf("%*.1zu", first ? (first = 0) : 7, nw);
|
|
if (cmode || noflags)
|
|
printf("%*.1zu", first ? (first = 0) : 7, nc);
|
|
if (str)
|
|
printf(" %s", str);
|
|
putchar('\n');
|
|
}
|
|
|
|
static void
|
|
wc(FILE *fp, const char *str)
|
|
{
|
|
int word = 0, rlen;
|
|
Rune c;
|
|
size_t nc = 0, nl = 0, nw = 0;
|
|
|
|
while ((rlen = efgetrune(&c, fp, str))) {
|
|
nc += (cmode == 'c' || !cmode) ? rlen : (c != Runeerror);
|
|
if (c == '\n')
|
|
nl++;
|
|
if (!isspacerune(c))
|
|
word = 1;
|
|
else if (word) {
|
|
word = 0;
|
|
nw++;
|
|
}
|
|
}
|
|
if (word)
|
|
nw++;
|
|
tc += nc;
|
|
tl += nl;
|
|
tw += nw;
|
|
output(str, nc, nl, nw);
|
|
}
|
|
|
|
static void
|
|
usage(void)
|
|
{
|
|
eprintf("usage: %s [-c | -m] [-lw] [file ...]\n", argv0);
|
|
}
|
|
|
|
int
|
|
main(int argc, char *argv[])
|
|
{
|
|
FILE *fp;
|
|
int many;
|
|
int ret = 0;
|
|
|
|
ARGBEGIN {
|
|
case 'c':
|
|
cmode = 'c';
|
|
break;
|
|
case 'm':
|
|
cmode = 'm';
|
|
break;
|
|
case 'l':
|
|
lflag = 1;
|
|
break;
|
|
case 'w':
|
|
wflag = 1;
|
|
break;
|
|
default:
|
|
usage();
|
|
} ARGEND;
|
|
|
|
if (!argc) {
|
|
wc(stdin, NULL);
|
|
} else {
|
|
for (many = (argc > 1); *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;
|
|
}
|
|
wc(fp, *argv);
|
|
if (fp != stdin && fshut(fp, *argv))
|
|
ret = 1;
|
|
}
|
|
if (many)
|
|
output("total", tc, tl, tw);
|
|
}
|
|
|
|
return !!(fshut(stdin, "<stdin>") + fshut(stdout, "<stdout>")) || ret;
|
|
}
|