10 Directory Tree


Of all the programming tasks, I’m embarrassed to admit that I enjoy coding file utilities the most. The casual user is unaware of the mountain of information about files provided by the operating system. It’s highly detailed low-hanging fruit, eager for plucking. Plus, exploring files and directories opens your understanding of how computer storage works. Exploring this field may inspire you to write your own, interesting file utilities. If it doesn’t, you can keep reading this chapter, your introduction to file systems and storage.

The goal here is to create a directory tree program. The output shows subdirectories as they sit in the hierarchical file system. In addition to being exposed to the word hierarchical (which I can amazingly both spell and type), in this chapter you learn how to:

  • Examine information about a file
  • Decipher file modes and permissions
  • Read a directory entry
  • Use recursion to explore the directory structure
  • Extract a directory name from a full pathname
  • Output a directory tree
  • Avoid confusing the word hierarchical with hieroglyphical

Before diving into the details, be aware that GUI nomenclature prefers the term folder over directory. As a C programmer, you must use the term directory, not folder. All C functions that deal with files and directories use directory or contain the abbreviation “dir.” Don’t wimp out and use the term folder.

10.1 The File System

10.2 File and Directory Details

10.2.1 Gathering file info

10.2.2 Exploring file type and permissions

10.2.3 Reading a directory

10.3 Subdirectory Exploration

10.3.1 Using directory exploration tools

10.3.2 Diving into a subdirectory

10.3.3 Mining deeper with recursion

10.4 A Directory Tree

10.4.1 Pulling out the directory name

10.4.2 Monitoring directory depth