The Linux Programming Interface

(nextflipdebug5) #1

360 Chapter 18


FTW_SL
This is a symbolic link. This value is returned only if nftw() is called with the
FTW_PHYS flag.
FTW_SLN
This item is a dangling symbolic link. This value occurs only if FTW_PHYS was
not specified in the flags argument.
The fourth argument to func, ftwbuf, is pointer to a structure defined as follows:

struct FTW {
int base; /* Offset to basename part of pathname */
int level; /* Depth of file within tree traversal */
};

The base field of this structure is the integer offset of the filename part (the compo-
nent after the last /) of the pathname argument of func. The level field is the depth of
this item relative to the starting point of the traversal (which is level 0).
Each time it is called, func must return an integer value, and this value is inter-
preted by nftw(). Returning 0 tells nftw() to continue the tree walk, and if all calls to
func return 0, nftw() itself returns 0 to its caller. Returning a nonzero value tells
nftw() to immediately stop the tree walk, in which case nftw() returns the same non-
zero value as its return value.
Because nftw() uses dynamically allocated data structures, the only way that a
program should ever prematurely terminate a directory tree walk is by returning a
nonzero value from func. Using longjmp() (Section 6.8) to exit from func may lead to
unpredictable results—at the very least, memory leaks in a program.

Example program
Listing 18-3 demonstrates the use of nftw().

Listing 18-3: Using nftw() to walk a directory tree
––––––––––––––––––––––––––––––––––––––––––––––––– dirs_links/nftw_dir_tree.c
#define _XOPEN_SOURCE 600 /* Get nftw() and S_IFSOCK declarations */
#include <ftw.h>
#include "tlpi_hdr.h"

static void
usageError(const char *progName, const char *msg)
{
if (msg != NULL)
fprintf(stderr, "%s\n", msg);
fprintf(stderr, "Usage: %s [-d] [-m] [-p] [directory-path]\n", progName);
fprintf(stderr, "\t-d Use FTW_DEPTH flag\n");
fprintf(stderr, "\t-m Use FTW_MOUNT flag\n");
fprintf(stderr, "\t-p Use FTW_PHYS flag\n");
exit(EXIT_FAILURE);
}

static int /* Function called by nftw() */
dirTree(const char *pathname, const struct stat *sbuf, int type,
struct FTW *ftwb)
Free download pdf