Directory Recursion

If you need to recursively traverse a directory tree, there are two ways to do this:

  • Create tracks with increasing length as you walk, ... / ... / ... etc.

  • Use chdir to go to each directory when you come to it, so you never deal with names longer than two components.

The first method seems to me more obvious and can be more resistant to adverse events, such as something that is unmounted while you are halfway through it. On the other hand, while looking at the GNU search utility code, I notice that I am using the second method. Is there a reason for this? Any advantage of a second method that I haven't thought about?

+4
source share
3 answers

Erm ... in fact, the modern implementation most likely uses

ftw is short for file tree

See also a very useful resource: http://rosettacode.org/wiki/Walk_a_directory/Recursively#Library:_POSIX

+3
source

I believe find uses method 2 as you can execute commands as you go (with the exec option)

+2
source

Method 2, without visible actions, handles situations where a component in a path is renamed.

It also makes it impossible for anyone to unmount a directory during a search; the kernel will refuse to unmount the directory if it is used, which includes creating some process.

+2
source

All Articles