Team-FLY |
The exercises in this section develop programs to traverse directory trees in depth-first and breadth-first orders. Depth-first searches explore each branch of a tree to its leaves before looking at other branches. Breadth-first searches explore all the nodes at a given level before descending lower in the tree. Example 5.37For the file system tree in Figure 5.1 on page 146, depth-first ordering visits the nodes in the following order. / dirC my3.dat dirA dirB my1.dat my1.dat my2.dat The indentation of the filenames in Example 5.37 shows the level in the file system tree. Depth-first search is naturally recursive, as indicated by the following pseudocode. depthfirst(root) { for each node at or below root visit node; if node is a directory depthfirst(node); } Example 5.38For the file system tree in Figure 5.1, breadth-first order visits the nodes in the following order. / /dirC /dirA /dirC/my3.dat /dirA/dirB /dirA/my1.dat /dirA/my2.dat /dirA/dirB/my1.dat Breadth-first search can be implemented with a queue similar to the history queue of Program 2.8 on page 47. As the program encounters each directory node at a particular level, it enqueues the complete pathname for later examination. The following pseudocode assumes the existence of a queue. The enqueue operation puts a node at the end of the queue, and the dequeue operation removes a node from the front of the queue. breadthfirst(root){ enqueue(root); while (queue is not empty) { dequeue(&next); for each node directly below next: visit the node if node is a directory enqueue(node) } } Exercise 5.39The UNIX du shell command is part of the POSIX:UP Extension. The command displays the sizes of the subdirectories of the tree rooted at the directory specified by its command-line argument. If called with no directory, the du utility uses the current working directory. If du is defined on your system, experiment with it. Try to determine which search strategy it uses to traverse the tree. Develop a program called mydu that uses a depth-first search strategy to display the sizes of the subdirectories in a tree rooted at the specified file.
|
Team-FLY |