sbase/wc.c

94 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 <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
2011-05-23 20:13:34 -04:00
#include <unistd.h>
2011-05-22 21:36:34 -04: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[])
{
bool many;
2011-05-23 20:13:34 -04:00
char c;
2011-05-22 21:36:34 -04:00
FILE *fp;
2011-05-23 20:13:34 -04:00
while((c = getopt(argc, argv, "clmw")) != -1)
switch(c) {
case 'c':
case 'm':
cmode = c;
break;
case 'l':
2011-05-22 21:36:34 -04:00
lflag = true;
2011-05-23 20:13:34 -04:00
break;
case 'w':
2011-05-22 21:36:34 -04:00
wflag = true;
break;
2011-05-23 20:13:34 -04:00
default:
exit(EXIT_FAILURE);
}
many = (argc > optind+1);
2011-05-22 21:36:34 -04:00
2011-05-23 20:13:34 -04:00
if(optind == argc)
2011-05-22 21:36:34 -04:00
wc(stdin, NULL);
2011-05-23 20:13:34 -04:00
else for(; optind < argc; optind++) {
if(!(fp = fopen(argv[optind], "r")))
eprintf("fopen %s:", argv[optind]);
wc(fp, argv[optind]);
2011-05-22 21:36:34 -04:00
fclose(fp);
}
if(many)
output("total", tc, tl, tw);
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);
fputc('\n', stdout);
}
void
wc(FILE *fp, const char *str)
{
bool word = false;
char c;
long nc = 0, nl = 0, nw = 0;
while((c = fgetc(fp)) != EOF) {
if(cmode != 'm' || (c & 0xc0) != 0x80)
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);
}