Recursive word count
A C program that walks files and folders and lists every word by how often it appears.
Give it any number of files and folders. Folders are walked recursively with the POSIX directory calls, reading only files that end in .txt and skipping anything whose name starts with a dot.
Each file is read and split into words by a set of careful rules: hyphens at the start or end of a word are dropped but hyphens inside stay (well-worn), apostrophes are part of the word (dog's), and digits split words apart. Counting is case-sensitive, so The and the are different words.
The counts are sorted by how often each word appears, and ties are broken alphabetically.
Files and folders
Directory walk
Recursive, .txt only, no hidden files
Word counter
Hyphens, apostrophes, digits
Sorted list
By count, then alphabetically
- Files and folders to Directory walk
- Directory walk to Word counter
- Word counter to Sorted list
See it work
A sample folder
| File | Contents | Read? |
|---|---|---|
| notes/a.txt | The cat sat on the mat. The dog's bed is a well-worn mat. | Yes |
| notes/old/b.txt | A cat and a dog -- friends. | Yes, found by recursion |
| notes/.drafts/c.txt | secret secret secret | No, hidden folder |
| notes/todo.md | skipped skipped | No, not .txt |
What it printed
$ ./words notesThe 2a 2cat 2mat 2A 1and 1bed 1dog 1dog's 1friends 1is 1on 1sat 1the 1well-worn 1
The real output. secret and skipped never appear, well-worn and dog's stay whole, and capitals sort before lowercase.