int ftw (const char dir, int (fn)(const char *file, const struct stat *sb, int flag), int depth);
ftw() walks through the directory tree starting from the indicated directory dir. For each found entry in the tree, it calls fn() with the full pathname of the entry, a pointer to the stat(2) structure for the entry and an int flag, which value will be one of the following:
Item is a normal file
Item is a directory
Item is a directory which can't be read
Item is a symbolic link
The stat failed on the item which is not a symbolic link
If the item is a symbolic link and stat failed, XPG4v2 states that it is undefined whether FTW_NS or FTW_SL is used.
ftw() recursively calls itself for traversing found directories, handling a directory before its files or subdirectories. To avoid using up all a program's file descriptors, the depth specifies the number of simultaneous open directories. When the depth is exceeded, ftw() will become slower because directories have to be closed and reopened. ftw() uses at most one file descriptor for each level in the file hierarchy.
Because ftw() uses dynamic data structures, the only safe way to exit out of a tree walk is to return a non-zero value. To handle interrupts, for example, mark that the interrupt occurred and return a non-zero value--don't use longjmp(3) unless the program is going to terminate.
The function nftw() does precisely the same as ftw(), except that it has one additional argument flags (and calls the supplied function with one more argument). This flags argument is an OR of zero or more of the following flags:
If set, do a chdir() to each directory before handling its contents.
If set, do a depth-first search, that is, call the function for the directory itself only after handling the contents of the directory and its subdirectories.
If set, stay within the same file system.
If set, do not follow symbolic links. (This is what you want.) If not set, symbolic links are followed, but no file is reported twice.
If FTW_PHYS is not set, but FTW_DEPTH is set, then the function fn() is never called for a directory that would be a descendant of itself.
The function fn() is called with four arguments: the pathname of the reported entry, a pointer to a struct stat for this entry, an integer describing its type, and a pointer to a struct FTW. The type will be one of the following: FTW_F, FTW_D, FTW_DNR, FTW_SL, FTW_NS (with meaning as above; FTW_SL occurs only with FTW_PHYS set) or
Item is a directory and all its descendants have been handled already. (This occurs only with FTW_DEPTH set.)
Item is a symbolic link pointing to a nonexisting file. (This occurs only with FTW_PHYS unset.)