Chapter 12. Fortunate Son

Now I laugh and make a fortune / Off the same ones that I tortured

They Might Be Giants, “Kiss Me, Son of God” (1988)

In this chapter, you will create a Rust version of the fortune program that will print a randomly selected aphorism or bit of trivia or interesting ASCII art1 from a database of text files. The program gets its name from a fortune cookie, a crisp cookie that contains a small piece of paper printed with a short bit of text that might be a fortune like “You will take a trip soon” or maybe a short joke or saying. When I was first learning to use a Unix terminal in my undergraduate days,2 a successful login would often include the output from fortune.

You will learn how to do the following:

  • Use the Path and PathBuf structs to represent system paths

  • Parse records of text spanning multiple lines from a file

  • Use randomness and control it with seeds

  • Use the OsStr and OsString types to represent filenames

How fortune Works

I will start by describing how fortune works so you will have an idea of what your version will need to do. You may first need to install the program,3 as it is not often present by default on most systems. Here’s a bit of the manual page, which you can read with man fortune:

NAME fortune - print a random, hopefully interesting, adage SYNOPSIS fortune [-acefilosuw] [-n length] [ -m pattern] [[n%] file/dir/all] DESCRIPTION When fortune is run with no arguments it prints out a random epigram. Epigrams are divided ...

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.