#include <stdio.h>
#include <ftw.h>

/****
 *
 * Example use of nftw.
 *
 */

/**
 * The visit function is called by nftw for each element of a traversed
 * directory hierarchy.  It prints out the path of the element being visited,
 * and its mode as an octal value.  The first three octits of the mode are the
 * file type, with 040 indicating a directory, and 100 a plain file.  The last
 * three octits are the file permissions, e.g., 644 = "rw-r--r--".
 *
 * Note that the visit function must return 0 in order for nftw to continue the
 * travesal.  Per the nftw man page, a non-zero return value from the visit
 * function means that nftw will discontinue the traversal.
 */
int visit(const char* path, const struct stat* stat, int flags, struct FTW* ftw) {
    printf("path=%s, mode=%o\n", path, stat->st_mode);
    return 0;
}

/**
 * The main function just calls nftw, catching any error it might return.  If
 * argv[1] is non-null, it sends that as the path to nftw.  Otherwise it sends
 * "." as the path.
 */
int main(int argc, char** argv) {
    if (nftw(argc >= 2 ? argv[1] : ".", visit, 10, 0) != 0) {
        perror("nftw");
    }
}