wc

This example is an implementation of wc, a standard Unix program that counts characters, words, and lines in one or more files. The counts for each file given on the command line are printed, followed by a summary of totals for all files.

Source code

/*
 * Copyright © 2006 Alistair Crooks.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote
 *    products derived from this software without specific prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
 * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

// Small program to count words

totchars = totwords = totlines = 0;

void
pnums(int lines, int words, int chars, string f)
{
	printf("\t%d\t%d\t%d\t%s\n", lines, words, chars, f);
}

// open file `f' and count chars, words and lines
void
wc(string f)
{
	chars = words = lines = 0;
	inword = 0;

	if (f == "") {
		fp = stdin;
	} else {
		// open the file and check it worked
		fp = fopen(f, "r");
		if (is_void(fp)) {
			err = sprintf("%s isn't a valid file", f);
			throw(err);
		}
	}
	for (;;) {
		s = fgets(fp);
		if (is_void(s)) 
			break;
		for (i = 0 ; i < strlen(s) ; i++) {
			chars += 1;
			ch = substr(s, i, 1);
			if (isspace(ch)) {
				if (ch == '\n') {
					lines += 1;
				}
				if (inword) {
					inword = 0;
					words += 1;
				}
			} else {
				inword = 1;
			}
		}
	}
	if (f != "") {
		fclose(fp);
	}

	// add file values onto global totals
	totchars += chars;
	totwords += words;
	totlines += lines;
	global("totchars", "totwords", "totlines");

	// print file values
	pnums(lines, words, chars, f);
}

if (argc < 2) {
	wc("");
} else {
	for (i = 1 ; i < argc ; i++) {
		try {
			wc(argv[i]);
		} catch (e) {
			print("Exception \x22", e, "\x22 occurred\n");
		}
	}
	// print the totals
	pnums(totlines, totwords, totchars, "totals");
}