aboutsummaryrefslogtreecommitdiffstats
path: root/c/wc.c
blob: 86c3aed99cc6e4c845bffe88dfcebfb8b28532f0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include "gbos.h"
/* wc [-l] [-w] [-c]: count lines, words, chars of stdin (default: all). */
void main(void) {
    char *argv[8];
    unsigned char argc = argv_parse(argv, 8);
    unsigned char wl = hasflag(argv, argc, 'l');
    unsigned char ww = hasflag(argv, argc, 'w');
    unsigned char wch = hasflag(argv, argc, 'c');
    unsigned int lines = 0, words = 0, chars = 0;
    unsigned char inword = 0, first = 1;
    char c;
    if (!wl && !ww && !wch) { wl = ww = wch = 1; }
    for (;;) {
        c = readc();
        if (c == EOF) break;
        chars++;
        if (c == '\n') lines++;
        if (c == ' ' || c == '\n' || c == '\r' || c == '\t') inword = 0;
        else if (!inword) { inword = 1; words++; }
    }
    if (wl)  { putu(lines); first = 0; }
    if (ww)  { if (!first) putc(' '); putu(words); first = 0; }
    if (wch) { if (!first) putc(' '); putu(chars); }
    nl();
}