Movatterモバイル変換


[0]ホーム

URL:


man7.org > Linux >man-pages

Linux/UNIX system programming training


ftw(3) — Linux manual page

NAME |LIBRARY |SYNOPSIS |DESCRIPTION |RETURN VALUE |ATTRIBUTES |VERSIONS |STANDARDS |HISTORY |NOTES |BUGS |EXAMPLES |SEE ALSO |COLOPHON

ftw(3)                   Library Functions Manualftw(3)

NAME        top

       ftw, nftw - file tree walk

LIBRARY        top

       Standard C library (libc,-lc)

SYNOPSIS        top

#include <ftw.h>int nftw(const char *dirpath,typeof(int (const char *fpath, const struct stat *sb,inttypeflag, struct FTW *ftwbuf))*fn,intnopenfd, intflags);[[deprecated]]int ftw(const char *dirpath,typeof(int (const char *fpath, const struct stat *sb,inttypeflag))*fn,intnopenfd);   Feature Test Macro Requirements for glibc (seefeature_test_macros(7)):nftw():           _XOPEN_SOURCE >= 500

DESCRIPTION        top

nftw() walks through the directory tree that is located under the       directorydirpath, and callsfn() once for each entry in the tree.       By default, directories are handled before the files and       subdirectories they contain (preorder traversal).       To avoid using up all of the calling process's file descriptors,nopenfd specifies the maximum number of directories thatnftw()       will hold open simultaneously.  When the search depth exceeds       this,nftw() will become slower because directories have to be       closed and reopened.nftw() uses at most one file descriptor for       each level in the directory tree.       For each entry found in the tree,nftw() callsfn() with four       arguments:fpath,sb,typeflag, andftwbuf.fpath is the pathname       of the entry, and is expressed either as a pathname relative to       the calling process's current working directory at the time of the       call tonftw(), ifdirpath was expressed as a relative pathname,       or as an absolute pathname, ifdirpath was expressed as an       absolute pathname.sb is a pointer to thestat structure returned       by a call tostat(2) forfpath.       Thetypeflag argument passed tofn() is an integer that has one of       the following values:FTW_Ffpath is a regular file.FTW_Dfpath is a directory.FTW_DNRfpath is a directory which can't be read.FTW_DPfpath is a directory, andFTW_DEPTHwas specified inflags.              (IfFTW_DEPTHwas not specified inflags, then directories              will always be visited withtypeflag set toFTW_D.)  All of              the files and subdirectories withinfpath have been              processed.FTW_NSThestat(2) call failed onfpath, which is not a symbolic              link.  The probable cause for this is that the caller had              read permission on the parent directory, so that the              filenamefpath could be seen, but did not have execute              permission, so that the file could not be reached forstat(2).  The contents of the buffer pointed to bysb are              undefined.FTW_SLfpath is a symbolic link, andFTW_PHYSwas set inflags.FTW_SLNfpath is a symbolic link pointing to a nonexistent file.              (This occurs only ifFTW_PHYSis not set.)  In this case              thesb argument passed tofn() contains information              returned by performinglstat(2) on the "dangling" symbolic              link.  (But see BUGS.)       The fourth argument (ftwbuf) thatnftw() supplies when callingfn() is a pointer to a structure of typeFTW:           struct FTW {               int base;               int level;           };base is the offset of the filename (i.e., basename component) in       the pathname given infpath.level is the depth offpath in the       directory tree, relative to the root of the tree (dirpath, which       has depth 0).       To stop the tree walk,fn() returns a nonzero value; this value       will become the return value ofnftw().  As long asfn() returns       0,nftw() will continue either until it has traversed the entire       tree, in which case it will return zero, or until it encounters an       error (such as amalloc(3) failure), in which case it will return       -1.       Becausenftw() uses dynamic data structures, the only safe way to       exit out of a tree walk is to return a nonzero value fromfn().       To allow a signal to terminate the walk without causing a memory       leak, have the handler set a global flag that is checked byfn().Don't uselongjmp(3) unless the program is going to terminate.       Theflags argument ofnftw() is formed by ORing zero or more of       the following flags:FTW_ACTIONRETVAL(since glibc 2.3.3)              If this glibc-specific flag is set, thennftw() handles the              return value fromfn() differently.fn() should return one              of the following values:FTW_CONTINUE                     Instructsnftw() to continue normally.FTW_SKIP_SIBLINGS                     Iffn() returns this value, then siblings of the                     current entry will be skipped, and processing                     continues in the parent.FTW_SKIP_SUBTREE                     Iffn() is called with an entry that is a directory                     (typeflag isFTW_D), this return value will prevent                     objects within that directory from being passed as                     arguments tofn().nftw() continues processing with                     the next sibling of the directory.FTW_STOP                     Causesnftw() to return immediately with the return                     valueFTW_STOP.              Other return values could be associated with new actions in              the future;fn() should not return values other than those              listed above.              The feature test macro_GNU_SOURCEmust be defined (before              includingany header files) in order to obtain the              definition ofFTW_ACTIONRETVALfrom<ftw.h>.FTW_CHDIR              If set, do achdir(2) to each directory before handling its              contents.  This is useful if the program needs to perform              some action in the directory in whichfpath resides.              (Specifying this flag has no effect on the pathname that is              passed in thefpath argument offn.)FTW_DEPTH              If set, do a post-order traversal, that is, callfn() for              the directory itselfafter handling the contents of the              directory and its subdirectories.  (By default, each              directory is handledbefore its contents.)FTW_MOUNT              If set, stay within the same filesystem (i.e., do not cross              mount points).FTW_PHYS              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.              IfFTW_PHYSis not set, butFTW_DEPTHis set, then the              functionfn() is never called for a directory that would be              a descendant of itself.ftw()ftw() is an older function that offers a subset of the       functionality ofnftw().  The notable differences are as follows:       •ftw() has noflags argument.  It behaves the same as whennftw() is called withflags specified as zero.       •  The callback function,fn(), is not supplied with a fourth          argument.       •  The range of values that is passed via thetypeflag argument          supplied tofn() is smaller: justFTW_F,FTW_D,FTW_DNR,FTW_NS, and (possibly)FTW_SL.

RETURN VALUE        top

       These functions return 0 on success, and -1 if an error occurs.       Iffn() returns nonzero, then the tree walk is terminated and the       value returned byfn() is returned as the result offtw() ornftw().       Ifnftw() is called with theFTW_ACTIONRETVALflag, then the only       nonzero value that should be used byfn() to terminate the tree       walk isFTW_STOP, and that value is returned as the result ofnftw().

ATTRIBUTES        top

       For an explanation of the terms used in this section, seeattributes(7).       ┌──────────────────────────────────┬───────────────┬─────────────┐       │InterfaceAttributeValue│       ├──────────────────────────────────┼───────────────┼─────────────┤       │nftw()                           │ Thread safety │ MT-Safe cwd │       ├──────────────────────────────────┼───────────────┼─────────────┤       │ftw()                            │ Thread safety │ MT-Safe     │       └──────────────────────────────────┴───────────────┴─────────────┘

VERSIONS        top

       In some implementations (e.g., glibc),ftw() will never useFTW_SL; on other systemsFTW_SLoccurs only for symbolic links       that do not point to an existing file; and again on other systemsftw() will useFTW_SLfor each symbolic link.  Iffpath is a       symbolic link andstat(2) failed, POSIX.1-2008 states that it is       undefined whetherFTW_NSorFTW_SLis passed intypeflag.  For       predictable results, usenftw().

STANDARDS        top

       POSIX.1-2008.

HISTORY        top

ftw()  POSIX.1-2001, SVr4, SUSv1.  POSIX.1-2008 marks it as              obsolete.nftw() glibc 2.1.  POSIX.1-2001, SUSv1.FTW_SLPOSIX.1-2001, SUSv1.

NOTES        top

       POSIX.1-2008 notes that the results are unspecified iffn does not       preserve the current working directory.

BUGS        top

       According to POSIX.1-2008, when thetypeflag argument passed tofn() containsFTW_SLN, the buffer pointed to bysb should contain       information about the dangling symbolic link (obtained by callinglstat(2) on the link).  Early glibc versions correctly followed       the POSIX specification on this point.  However, as a result of a       regression introduced in glibc 2.4, the contents of the buffer       pointed to bysb were undefined whenFTW_SLNis passed intypeflag.  (More precisely, the contents of the buffer were left       unchanged in this case.)  This regression was eventually fixed in       glibc 2.30, so that the glibc implementation (once more) follows       the POSIX specification.

EXAMPLES        top

       The following program traverses the directory tree under the path       named in its first command-line argument, or under the current       directory if no argument is supplied.  It displays various       information about each file.  The second command-line argument can       be used to specify characters that control the value assigned to       theflags argument when callingnftw().Program source       #define _XOPEN_SOURCE 500       #include <ftw.h>       #include <stdint.h>       #include <stdio.h>       #include <stdlib.h>       #include <string.h>       static int       display_info(const char *fpath, const struct stat *sb,                    int tflag, struct FTW *ftwbuf)       {           printf("%-3s %2d ",                  (tflag == FTW_D) ?   "d"   : (tflag == FTW_DNR) ? "dnr" :                  (tflag == FTW_DP) ?  "dp"  : (tflag == FTW_F) ?   "f" :                  (tflag == FTW_NS) ?  "ns"  : (tflag == FTW_SL) ?  "sl" :                  (tflag == FTW_SLN) ? "sln" : "???",                  ftwbuf->level);           if (tflag == FTW_NS)               printf("-------");           else               printf("%7jd", (intmax_t) sb->st_size);           printf("   %-40s %d %s\n",                  fpath, ftwbuf->base, fpath + ftwbuf->base);           return 0;           /* To tell nftw() to continue */       }       int       main(int argc, char *argv[])       {           int flags = 0;           if (argc > 2 && strchr(argv[2], 'd') != NULL)               flags |= FTW_DEPTH;           if (argc > 2 && strchr(argv[2], 'p') != NULL)               flags |= FTW_PHYS;           if (nftw((argc < 2) ? "." : argv[1], display_info, 20, flags)               == -1)           {               perror("nftw");               exit(EXIT_FAILURE);           }           exit(EXIT_SUCCESS);       }

SEE ALSO        top

stat(2),fts(3),readdir(3)

COLOPHON        top

       This page is part of theman-pages (Linux kernel and C library       user-space interface documentation) project.  Information about       the project can be found at        ⟨https://www.kernel.org/doc/man-pages/⟩.  If you have a bug report       for this manual page, see       ⟨https://git.kernel.org/pub/scm/docs/man-pages/man-pages.git/tree/CONTRIBUTING⟩.       This page was obtained from the tarball man-pages-6.15.tar.gz       fetched from       ⟨https://mirrors.edge.kernel.org/pub/linux/docs/man-pages/⟩ on       2025-08-11.  If you discover any rendering problems in this HTML       version of the page, or you believe there is a better or more up-       to-date source for the page, or you have corrections or       improvements to the information in this COLOPHON (which isnot       part of the original manual page), send a mail to       man-pages@man7.orgLinux man-pages 6.15            2025-05-17ftw(3)

Pages that refer to this page:fts(3)readdir(3)attributes(7)



HTML rendering created 2025-09-06 byMichael Kerrisk, author ofThe Linux Programming Interface.

For details of in-depthLinux/UNIX system programming training courses that I teach, lookhere.

Hosting byjambit GmbH.

Cover of TLPI


[8]ページ先頭

©2009-2025 Movatter.jp