9p / who / tweedy / 9C / 1
Word Counting
Code
#include <u.h>
#include <libc.h>
#include <bio.h>
#define STDIN 0
#define IN 1 /* inside a word */
#define OUT 0 /* outside a word */
/* count lines, words, and characters in input */
void
main()
{
Biobuf *bstdin;
bstdin = Bfdopen(STDIN, OREAD);
int c, nl, nw, nc, state;
state = OUT;
nl = nw = nc = 0;
while((c = Bgetc(bstdin)) >= 0){
++nc;
if(c == '\n')
++nl;
if(c == ' ' || c == '\n' || c == '\t')
state = OUT;
else if(state == OUT){
state = IN;
++nw;
}
}
print("%ud\t%ud\t%ud\n", nl, nw, nc);
exits(0);
}
Output
$ 9c words.c; 9l words.o -o words
$ ./words < words.c
35 95 514
tweedy