I am trying to recursively iterate a folder using the nftw() function of C for printing the complete Directory Structure along with that I can't find a way to check whether the level has changed ,i.e, it has moved inside a directory or is iterating in the directory only. So, is there any way I can check for change in level using nftw()?
If you read the POSIX specification of nftw()
, you'll find:
At each file it encounters,
nftw()
shall call the user-supplied functionfn
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 ofbase
is the offset of the object's filename in the pathname passed as the first argument tofn
. The value oflevel
indicates depth relative to the root of the walk, where the root level is 0.
So, the answer to your question is that the level
element of the FTW object tells you the level of the current item. If you need to spot changes, you'll need to keep track of the previous level, somehow — it likely will be a file scope variable.
It would be nice if there was a variant of nftw()
(call it nftw2()
) that made provision for a user-supplied 'extra information' argument — a void *
that would be passed to nftw2()
and which nftw2()
would relay to the called function. Then you'd not need the file scope variable.
The BSD, macOS and Linux systems, at least, have an alternative to nftw()
— the fts(3)
functions (also at FreeBSD). The macOS manual says they might be a part of a future version of POSIX, but they're not a part of POSIX 2017. (I don't see the extra information parameter here, either — oh well! If you're ever designing a callback system, consider providing a context (or 'extra information') parameter that can be used.)