使用 nftw() 遍历文件夹时检查级别变化

Check for level change while traversing folder using nftw()

我正在尝试使用 C 的 nftw() 函数递归迭代文件夹以打印完整的目录结构,同时我找不到检查级别是否已更改的方法,即它是否已移动在目录内或仅在目录中迭代。那么,有什么方法可以使用 nftw() 检查级别的变化吗?

如果您阅读 nftw() 的 POSIX 规范,您会发现:

At each file it encounters, nftw() shall call the user-supplied function fn with four arguments:

  • The first argument is the pathname of the object.

  • The second argument is a pointer to the stat buffer containing information on the object…

  • The third argument is an integer giving additional information. Its value is one of the following:

    • FTW_D — The object is a directory.
  • The fourth argument is a pointer to an FTW structure. The value of base is the offset of the object's filename in the pathname passed as the first argument to fn. The value of level indicates depth relative to the root of the walk, where the root level is 0.

因此,您问题的答案是 FTW 对象的 level 元素告诉您当前项目的级别。如果您需要发现更改,则需要以某种方式跟踪上一级别 — 它可能是文件范围变量。

如果有一个 nftw() 的变体(称之为 nftw2()),它为用户提供的 'extra information' 参数提供了条件,那就太好了 — void *那将被传递给 nftw2() 并且 nftw2() 将传递给被调用的函数。那么你就不需要文件范围变量了。

BSD、macOS 和 Linux 系统至少可以替代 nftw()fts(3) functions (also at FreeBSD)。 macOS 手册说它们可能是 POSIX 未来版本的一部分,但它们不是 POSIX 2017 的一部分。(我在这里也没有看到额外的信息参数——哦好吧!如果您曾经设计过回调系统,请考虑提供一个可以使用的上下文(或 'extra information')参数。)