Search Directories: Recursion Examples

Searching/traversing directories is a natural example of recursion since directory hierarchies are recursive. A directory contains files and other directories.

The classes DirEntry and DirStream make traversing directories simple. The classes linked here run under windows, I've tested them with several compilers. Note: these classes are 32-bit windows classes, e.g., not for Turbo 3.0. There are versions of these classes that run under Linux/Unix, see my book page for a link to the code.

Here's a function that prints all the entries, both files and subdirectories, in the directory dirName.

void PrintDir(const apstring& dirName) { DirStream input(dirName); for(input.Init(); input.HasMore(); input.Next()) { DirEntry entry = input.Current(); cout << entry.Name() << "\t" << entry.Size() << endl; } } That's it! The function prints the names of every file/subdirectory and the file size. For recursion, the program subdir.cpp prints everything, all the way down: subdirectories and their contents, and their subdirectory contents and so on.

The class implementations are here:


Owen L. Astrachan
Last modified: Tue May 11 19:48:16 EDT 1999