Main Content

Searching through all the files in or below a directory - Ruby, Tcl, Perl

Archive - Originally posted on "The Horse's Mouth" - 2011-09-09 20:24:09 - Graham Ellis

Many of our customers want to learn how to traverse all the files in a directory, or perhaps even all the files in or below a directory. I quite often write a demonstration program during our courses which looks though part of a file system tree for files over a certain size, or for the largest (so many) files. It's a neat and useful demosntration of an application which most people can identify with.

See examples in Ruby, Tcl and Perl.

The method used is to keep a queue of directories to be checked in a list / array, and travese them one at a time. As new directories are found, they're added onto the end of the list / array, and as each directory is traversed, it's removed from the array, And when the array is empty, the program is done.

It's been suggested to me that when a directory is found within another ditrectory, the traversing of the parent should be suspended while the child (and any children it has) are handled. That can be done neatly through recurrsion, but the code ends up being a bit too "clever" to be easy to follow and - unless you need to traverse in a certain order - it's unnecessary.