Chapter 5. Word to Your Mother

All hail the dirt bike / Philosopher dirt bike / Silence as we gathered round / We saw the word and were on our way

They Might Be Giants, “Dirt Bike” (1994)

For this chapter’s challenge, you will create a version of the venerable wc (word count) program, which dates back to version 1 of AT&T Unix. This program will display the number of lines, words, and bytes found in text from STDIN or one or more files. I often use it to count the number of lines returned by some other process.

In this chapter, you will learn how to do the following:

  • Use the Iterator::all function

  • Create a module for unit tests

  • Fake a filehandle for testing

  • Conditionally format and print a value

  • Conditionally compile a module when testing

  • Break a line of text into words, bytes, and characters

How wc Works

I’ll start by showing how wc works so you know what is expected by the tests. Following is an excerpt from the BSD wc manual page that describes the elements that the challenge program will implement:

WC(1) BSD General Commands Manual WC(1) NAME wc -- word, line, character, and byte count SYNOPSIS wc [-clmw] [file ...] DESCRIPTION The wc utility displays the number of lines, words, and bytes contained in each input file, or standard input (if no file is specified) to the standard output. A line is defined as a string of characters delimited by a <newline> character. Characters beyond the final <newline> charac- ter will not be included in the line count. ...

Get Command-Line Rust now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.