Finding the Dictionary

My first Unix System Administrator job was pretty routine: I did backups. It was only later that I discovered some of the many nerdy treasures available in that operating system.

One of the Unix treasures (shared by Linux and macOS) is the dictionary. It’s a text file containing words, but not the definitions. The dictionary most likely came about to assist with spell-checking. For example, the spell command uses the dictionary. Beyond that, someone somewhere at some time decided that Unix needed a dictionary. It has one.

The dictionary file may not be installed on your Linux distro. Use the Linux package manager, such as apt, to obtain a dictionary. Different types are available for every language and variation. For example, English dictionaries include British, American, and Canadian versions. Then you can elect to install small, medium, or large dictionaries. The size is based on the number of words included.

As with any file on your computer, you can use your C programming kung fu to access and examine the dictionary file’s contents. You can search for words, word patterns, or even code a program to pluck out random words and have your computer blabber at you. The process starts by obtaining and installing the dictionary and then accessing its file.

The dictionary traditionally dwelles in the /usr/share/dict directory, though the location may be different on a given system. The dictionary name is different as well, depending on the version you install. For example, on my computer the file is named american-english. Even so, the installer creates an alias words that reference the dictionary file no matter what its true name.

The following code performs a test to ensure that the named dictionary file is installed and available. The defined constant DICTIONARY is set equal to the dictionary file’s full pathname. Remember to change it on your own system if necessary.

2023_10_07-Lesson.c

/* Look up the dictionary */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#define DICTIONARY "/usr/share/dict/words"

int main()
{
    int r;

    r = access(DICTIONARY,F_OK);
    if( r==-1 )
        puts("Dictionary file is not installed");
    else
        puts("Dictionary file is installed");

    return(0);
}

This code uses the access() function to determine whether the file exists. You can refer to my Lesson on the access() function for more details.

Here’s a sample run:

Dictionary file is installed

Once confirmed that the dictionary file is installed, you can access its contents in your C programs. Think of the fun you can have! I plunge into this topic starting with next week’s Lesson.

Leave a Reply