2011-05-23 01:36:34 +00:00
|
|
|
/* See LICENSE file for copyright and license details. */
|
|
|
|
#include <ctype.h>
|
|
|
|
#include <stdbool.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
2011-05-24 00:13:34 +00:00
|
|
|
#include <unistd.h>
|
2011-05-23 01:36:34 +00:00
|
|
|
#include "util.h"
|
|
|
|
|
|
|
|
static void output(const char *, long, long, long);
|
|
|
|
static void wc(FILE *, const char *);
|
|
|
|
|
|
|
|
static bool lflag = false;
|
|
|
|
static bool wflag = false;
|
|
|
|
static char cmode = 0;
|
|
|
|
static long tc = 0, tl = 0, tw = 0;
|
|
|
|
|
|
|
|
int
|
|
|
|
main(int argc, char *argv[])
|
|
|
|
{
|
|
|
|
FILE *fp;
|
2013-03-11 00:12:10 +00:00
|
|
|
int i;
|
2013-07-20 05:27:42 +00:00
|
|
|
|
2013-03-11 00:12:10 +00:00
|
|
|
ARGBEGIN {
|
|
|
|
case 'c':
|
|
|
|
cmode = 'c';
|
|
|
|
break;
|
|
|
|
case 'm':
|
|
|
|
cmode = 'm';
|
|
|
|
break;
|
|
|
|
case 'l':
|
|
|
|
lflag = true;
|
|
|
|
break;
|
|
|
|
case 'w':
|
|
|
|
wflag = true;
|
|
|
|
break;
|
|
|
|
default:
|
|
|
|
eprintf("usage: %s [-clmw] [files...]\n", argv0);
|
|
|
|
} ARGEND;
|
2013-07-20 05:27:42 +00:00
|
|
|
|
2013-03-11 00:12:10 +00:00
|
|
|
if (argc == 0) {
|
2011-05-23 01:36:34 +00:00
|
|
|
wc(stdin, NULL);
|
2013-03-11 00:12:10 +00:00
|
|
|
} else {
|
|
|
|
for (i = 0; i < argc; i++) {
|
|
|
|
if(!(fp = fopen(argv[i], "r")))
|
|
|
|
eprintf("fopen %s:", argv[i]);
|
|
|
|
wc(fp, argv[i]);
|
|
|
|
fclose(fp);
|
|
|
|
}
|
|
|
|
if (argc > 1)
|
|
|
|
output("total", tc, tl, tw);
|
2011-05-23 01:36:34 +00:00
|
|
|
}
|
|
|
|
return EXIT_SUCCESS;
|
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
output(const char *str, long nc, long nl, long nw)
|
|
|
|
{
|
|
|
|
bool noflags = !cmode && !lflag && !wflag;
|
|
|
|
|
|
|
|
if(lflag || noflags)
|
|
|
|
printf(" %5ld", nl);
|
|
|
|
if(wflag || noflags)
|
|
|
|
printf(" %5ld", nw);
|
|
|
|
if(cmode || noflags)
|
|
|
|
printf(" %5ld", nc);
|
|
|
|
if(str)
|
|
|
|
printf(" %s", str);
|
2011-05-26 03:01:20 +00:00
|
|
|
putchar('\n');
|
2011-05-23 01:36:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void
|
|
|
|
wc(FILE *fp, const char *str)
|
|
|
|
{
|
|
|
|
bool word = false;
|
2013-07-20 11:09:42 +00:00
|
|
|
int c;
|
2011-05-23 01:36:34 +00:00
|
|
|
long nc = 0, nl = 0, nw = 0;
|
|
|
|
|
2011-06-10 03:14:05 +00:00
|
|
|
while((c = getc(fp)) != EOF) {
|
2011-06-08 20:30:33 +00:00
|
|
|
if(cmode != 'm' || UTF8_POINT(c))
|
2011-05-23 01:36:34 +00:00
|
|
|
nc++;
|
|
|
|
if(c == '\n')
|
|
|
|
nl++;
|
|
|
|
if(!isspace(c))
|
|
|
|
word = true;
|
|
|
|
else if(word) {
|
|
|
|
word = false;
|
|
|
|
nw++;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
tc += nc;
|
|
|
|
tl += nl;
|
|
|
|
tw += nw;
|
|
|
|
output(str, nc, nl, nw);
|
|
|
|
}
|