sbase/wc.c

104 lines
1.6 KiB
C
Raw Normal View History

2011-05-22 21:36:34 -04:00
/* See LICENSE file for copyright and license details. */
#include <stdio.h>
2011-05-23 20:13:34 -04:00
#include <unistd.h>
#include "utf.h"
2011-05-22 21:36:34 -04:00
#include "util.h"
static int lflag = 0;
static int wflag = 0;
static char cmode = 0;
static size_t tc = 0, tl = 0, tw = 0;
2011-05-22 21:36:34 -04:00
void
output(const char *str, size_t nc, size_t nl, size_t nw)
{
int noflags = !cmode && !lflag && !wflag;
2015-02-06 14:46:37 -05:00
int first = 1;
if (lflag || noflags)
2015-02-06 14:46:37 -05:00
printf("%*.zu", first ? (first = 0) : 7, nl);
if (wflag || noflags)
2015-02-06 14:46:37 -05:00
printf("%*.zu", first ? (first = 0) : 7, nw);
if (cmode || noflags)
2015-02-06 14:46:37 -05:00
printf("%*.zu", first ? (first = 0) : 7, nc);
if (str)
printf(" %s", str);
putchar('\n');
}
void
wc(FILE *fp, const char *str)
{
2015-02-01 05:22:11 -05:00
int word = 0, rlen;
Rune c;
size_t nc = 0, nl = 0, nw = 0;
while ((rlen = efgetrune(&c, fp, str))) {
2015-02-01 05:22:11 -05:00
nc += (cmode == 'c') ? rlen :
(c != Runeerror) ? 1 : 0;
if (c == '\n')
nl++;
2015-02-11 07:24:59 -05:00
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);
}
2011-05-22 21:36:34 -04:00
static void
usage(void)
{
eprintf("usage: %s [-c | -m] [-lw] [file ...]\n", argv0);
}
2011-05-22 21:36:34 -04:00
int
main(int argc, char *argv[])
{
FILE *fp;
2013-03-10 20:12:10 -04:00
int i;
2015-02-06 14:11:33 -05:00
int ret = 0;
2013-03-10 20:12:10 -04:00
ARGBEGIN {
case 'c':
cmode = 'c';
break;
case 'm':
cmode = 'm';
break;
case 'l':
lflag = 1;
2013-03-10 20:12:10 -04:00
break;
case 'w':
wflag = 1;
2013-03-10 20:12:10 -04:00
break;
default:
usage();
2013-03-10 20:12:10 -04:00
} ARGEND;
2013-03-10 20:12:10 -04:00
if (argc == 0) {
2011-05-22 21:36:34 -04:00
wc(stdin, NULL);
2013-03-10 20:12:10 -04:00
} else {
for (i = 0; i < argc; i++) {
if (!(fp = fopen(argv[i], "r"))) {
weprintf("fopen %s:", argv[i]);
2015-02-06 14:11:33 -05:00
ret = 1;
continue;
}
2013-03-10 20:12:10 -04:00
wc(fp, argv[i]);
fclose(fp);
}
if (argc > 1)
output("total", tc, tl, tw);
2011-05-22 21:36:34 -04:00
}
2015-02-06 14:11:33 -05:00
return ret;
2011-05-22 21:36:34 -04:00
}