Directory recursion

自闭症网瘾萝莉.ら 提交于 2019-12-18 17:26:53

问题


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

  1. Build up pathnames of increasing length as you go, .../.../... etc.

  2. Use chdir to step down into each directory as you come to it, so you are never dealing with pathnames longer than two components.

The first method strikes me as more obvious, and might be more robust against untoward events like something being unmounted while you are halfway through it. On the other hand, looking over the code for the GNU find utility, I notice it uses the second method. Is there a reason for that? Any advantage of the second method that I hadn't thought of?


回答1:


Erm... in fact a modern implementation will likely use the

  • ftw
  • nftw calls

ftw is short for file tree walk

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




回答2:


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




回答3:


The method 2 seemlessly handles situations where a component in the path is renamed.

It also denies anyone from unmounting the directory while it's being searched; the kernel will refuse to unmount the directory if it's in use, which includes being the cwd of some process.



来源:https://stackoverflow.com/questions/7377596/directory-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!