FTS(3)
๐ FTS(3) โ traverse a file hierarchy ๐
okay bestie, this is FTS(3) from the Library Functions Manual, and we're about to make file-hierarchy traversal make sense ๐โจ
โจ NAME โจ
fts โ traverse a file hierarchy ๐โจ
๐ LIBRARY ๐
Standard C Library (libc, -lc) ๐
๐งพ SYNOPSIS ๐งพ
#include <fts.h>
FTS *
fts_open(char * const *path_argv, int options,
int (*compar)(const FTSENT * const *, const FTSENT * const *));
FTS *
fts_open_b(char * const *path_argv, int options,
int (^compar)(const FTSENT * const *, const FTSENT * const *));
FTSENT *
fts_read(FTS *ftsp);
FTSENT *
fts_children(FTS *ftsp, int options);
int
fts_set(FTS *ftsp, FTSENT *f, int options);
void
fts_set_clientptr(FTS *ftsp, void *clientdata);
void *
fts_get_clientptr(FTS *ftsp);
FTS *
fts_get_stream(FTSENT *f);
int
fts_close(FTS *ftsp);
๐ฆ DESCRIPTION ๐ฆ
okay so the fts functions are literally your tour guides for traversing Unix file hierarchies ๐บ๏ธโจ the simple overview is that fts_open() and fts_open_b() return a โhandleโ on a file hierarchy, and then you supply that handle to the other fts functions. fts_read() returns a pointer to a structure describing one of the files in the file hierarchy. fts_children() returns a pointer to a linked list of structures, and each one describes one of the files contained in a directory in the hierarchy. in general, directories are visited two distinguishable times: in pre-order (before any of their descendants are visited) and in post-order (after all of their descendants have been visited). files are visited once. it is possible to walk the hierarchy โlogicallyโ (ignoring symbolic links) or physically (visiting symbolic links), order the walk of the hierarchy or prune and/or re-visit portions of the hierarchy ๐
two structures are defined (and typedef'd) in the include file <fts.h>. the first is FTS, the structure that represents the file hierarchy itself. the second is FTSENT, the structure that represents a file in the file hierarchy. normally, an FTSENT structure is returned for every file in the file hierarchy. in this manual page, โfileโ and โFTSENT structureโ are generally interchangeable ๐
the FTS structure contains space for a single pointer, which may be used to store application data or per-hierarchy state. the fts_set_clientptr() and fts_get_clientptr() functions may be used to set and retrieve this pointer. this is likely to be useful only when accessed from the sort comparison function, which can determine the original FTS stream of its arguments using the fts_get_stream() function. the two get functions are also available as macros of the same name ๐ซถ
the FTSENT structure contains at least the following fields, which are described in greater detail below:
typedef struct _ftsent {
int fts_info; /* status for FTSENT structure */
char *fts_accpath; /* access path */
char *fts_path; /* root path */
size_t fts_pathlen; /* strlen(fts_path) */
char *fts_name; /* file name */
size_t fts_namelen; /* strlen(fts_name) */
long fts_level; /* depth (-1 to N) */
int fts_errno; /* file errno */
long long fts_number; /* local numeric value */
void *fts_pointer; /* local address value */
struct ftsent *fts_parent; /* parent directory */
struct ftsent *fts_link; /* next file structure */
struct ftsent *fts_cycle; /* cycle structure */
struct stat *fts_statp; /* stat(2) information */
} FTSENT;
these fields are defined as follows:
fts_infoโ one of the following values describing the returnedFTSENTstructure and the file it represents. with the exception of directories without errors (FTS_D), all of these entries are terminal, that is, they will not be revisited, nor will any of their descendants be visited ๐คFTS_Dโ a directory being visited in pre-order.FTS_DCโ a directory that causes a cycle in the tree. (thefts_cyclefield of theFTSENTstructure will be filled in as well.)FTS_DEFAULTโ anyFTSENTstructure that represents a file type not explicitly described by one of the otherfts_infovalues.FTS_DNRโ a directory which cannot be read. this immediately followsFTS_D, in place ofFTS_DP, when the directory could not be entered, or could be entered but not read. this is an error return, and thefts_errnofield will be set to indicate what caused the error.FTS_DOTโ a file named.or..which was not specified as a file name tofts_open()orfts_open_b()(seeFTS_SEEDOT).FTS_DPโ a directory being visited in post-order. the contents of theFTSENTstructure will be unchanged from when the directory was visited in pre-order, except for thefts_infofield.FTS_ERRโ this is an error return, and thefts_errnofield will be set to indicate what caused the error.FTS_Fโ a regular file.FTS_NSโ a file for which nostat(2)information was available. the contents of thefts_statpfield are undefined. this is an error return, and thefts_errnofield will be set to indicate what caused the error.FTS_NSOKโ a file for which nostat(2)information was requested. the contents of thefts_statpfield are undefined.FTS_SLโ a symbolic link.FTS_SLNONEโ a symbolic link with a non-existent target. the contents of thefts_statpfield reference the file characteristic information for the symbolic link itself.
fts_accpathโ a path for accessing the file from the current directory.fts_pathโ the path for the file relative to the root of the traversal. this path contains the path specified tofts_open()orfts_open_b()as a prefix.fts_pathlenโ the length of the string referenced byfts_path.fts_nameโ the name of the file.fts_namelenโ the length of the string referenced byfts_name.fts_levelโ the depth of the traversal, numbered from-1toN, where this file was found. theFTSENTstructure representing the parent of the starting point (or root) of the traversal is numberedFTS_ROOTPARENTLEVEL(-1), and theFTSENTstructure for the root itself is numberedFTS_ROOTLEVEL(0).fts_errnoโ upon return of aFTSENTstructure from thefts_children()orfts_read()functions, with itsfts_infofield set toFTS_DNR,FTS_ERRorFTS_NS, thefts_errnofield contains the value of the external variableerrnospecifying the cause of the error. otherwise, the contents of thefts_errnofield are undefined.fts_numberโ this field is provided for the use of the application program and is not modified by theftsfunctions. it is initialized to0.fts_pointerโ this field is provided for the use of the application program and is not modified by theftsfunctions. it is initialized toNULL.fts_parentโ a pointer to theFTSENTstructure referencing the file in the hierarchy immediately above the current file, i.e., the directory of which this file is a member. a parent structure for the initial entry point is provided as well, however, only thefts_level,fts_numberandfts_pointerfields are guaranteed to be initialized.fts_linkโ upon return from thefts_children()function, thefts_linkfield points to the next structure in theNULL-terminated linked list of directory members. otherwise, the contents of thefts_linkfield are undefined.fts_cycleโ if a directory causes a cycle in the hierarchy (seeFTS_DC), either because of a hard link between two directories, or a symbolic link pointing to a directory, thefts_cyclefield of the structure will point to theFTSENTstructure in the hierarchy that references the same file as the currentFTSENTstructure. otherwise, the contents of thefts_cyclefield are undefined.fts_statpโ a pointer tostat(2)information for the file.
a single buffer is used for all of the paths of all of the files in the file hierarchy. therefore, the fts_path and fts_accpath fields are guaranteed to be NUL-terminated only for the file most recently returned by fts_read(). to use these fields to reference any files represented by other FTSENT structures will require that the path buffer be modified using the information contained in that FTSENT structure's fts_pathlen field. any such modifications should be undone before further calls to fts_read() are attempted. the fts_name field is always NUL-terminated ๐ซก๐
๐งต Thread Safety ๐งต
the fts functions can safely be used in multi-threaded programs provided no two threads access the same FTS or FTSENT structure simultaneously. however, unless the FTS_NOCHDIR flag was passed to fts_open() or fts_open_b(), calls to fts_read() and fts_children() may change the current working directory, which will affect all threads. conversely, changing the current working directory either during or between calls to fts_read() or fts_children() (even in a single-thread program) may cause fts to malfunction unless the FTS_NOCHDIR flag was passed to fts_open() or fts_open_b() and all paths in path_argv were absolute ๐ญโ ๏ธ
๐๏ธ fts_open() ๐๏ธ
the fts_open() function takes a pointer to an array of character pointers naming one or more paths which make up a logical file hierarchy to be traversed. the array must be terminated by a NULL pointer โจ
there are a number of options, at least one of which (either FTS_LOGICAL or FTS_PHYSICAL) must be specified. the options are selected by or'ing the following values:
FTS_COMFOLLOWโ this one makes any symbolic link specified as a root path get followed immediately, whether or notFTS_LOGICALis also specified ๐FTS_COMFOLLOWDIRโ same energy asFTS_COMFOLLOW, but only follows symbolic links to directories.FTS_LOGICALโ this makes theftsroutines returnFTSENTstructures for the targets of symbolic links instead of the symbolic links themselves. If this option is set, the only symbolic links for whichFTSENTstructures are returned to the application are those referencing non-existent files. EitherFTS_LOGICALorFTS_PHYSICALmust be provided to thefts_open()function. โญFTS_NOCHDIRโ okay so, to allow descending to arbitrary depths (independent of{PATH_MAX}) and improve performance, theftsfunctions change directories as they walk the file hierarchy. The side-effect is that an application cannot rely on being in any particular directory during the traversal.FTS_NOCHDIRturns off this feature, and theftsfunctions will not change the current directory. > Note that applications should not themselves change their current directory and try to access files unlessFTS_NOCHDIRis specified and absolute pathnames were provided as arguments tofts_open(). ๐ญFTS_NOSTATโ by default, returnedFTSENTstructures reference file characteristic information (thestatpfield) for each file visited. This option relaxes that requirement as a performance optimization, allowing theftsfunctions to set thefts_infofield toFTS_NSOKand leave the contents of thestatpfield undefined. โจFTS_NOSTAT_TYPEโ similar toFTS_NOSTAT, but it attempts to populatefts_infobased on information from thed_typefield ofstruct dirent. ๐ฆFTS_PHYSICALโ this makes theftsroutines returnFTSENTstructures for the symbolic links themselves instead of the target files they point to. If this option is set,FTSENTstructures for all symbolic links in the hierarchy are returned to the application. EitherFTS_LOGICALorFTS_PHYSICALmust be provided to thefts_open()function. ๐FTS_SEEDOTโ by default, unless they are specified as path arguments tofts_open(), any files named.or..encountered in the file hierarchy are ignored. This option causes theftsroutines to returnFTSENTstructures for them. ๐FTS_XDEVโ this one preventsftsfrom descending into directories that have a different device number than the file from which the descent began. ๐
Okay, now the compar argument ๐ โ it points to a user-defined function which may be used to order the traversal of the hierarchy. It takes two pointers to pointers to FTSENT structures as arguments and should return a negative value, zero, or a positive value to indicate if the file referenced by its first argument comes before, in any order with respect to, or after, the file referenced by its second argument. The fts_accpath, fts_path and fts_pathlen fields of the FTSENT structures may never be used in this comparison. If the fts_info field is set to FTS_NS or FTS_NSOK, the fts_statp field may not either. If the compar() argument is NULL, the directory traversal order is in the order listed in path_argv for the root paths, and in the order listed in the directory for everything else.
๐ฆ fts_open_b() ๐ฆ
The fts_open_b() function is identical to fts_open() except that it takes a block pointer instead of a function pointer. The block is copied before fts_open_b() returns, so the original can safely go out of scope or be released. ๐ซถ
๐ธ fts_read() ๐ธ
The fts_read() function returns a pointer to an FTSENT structure describing a file in the hierarchy. Directories (that are readable and do not cause cycles) are visited at least twice, once in pre-order and once in post-order. All other files are visited at least once. (Hard links between directories that do not cause cycles or symbolic links to symbolic links may cause files to be visited more than once, or directories more than twice.) ๐ตโ๐ซ
If all the members of the hierarchy have been returned, fts_read() returns NULL and sets the external variable errno to 0. If an error unrelated to a file in the hierarchy occurs, fts_read() returns NULL and sets errno appropriately. If an error related to a returned file occurs, a pointer to an FTSENT structure is returned, and errno may or may not have been set (see fts_info). Note that fts_read() will not set errno to 0 if called again with the same ftsp argument after the FTS_STOP flag has been set or the end of the stream has been reached. ๐
The FTSENT structures returned by fts_read() may be overwritten after a call to fts_close() on the same file hierarchy stream, or, after a call to fts_read() on the same file hierarchy stream unless they represent a file of type directory, in which case they will not be overwritten until after a call to fts_read() after the FTSENT structure has been returned by the fts_read() function in post-order. ๐
๐
fts_children() ๐
The fts_children() function returns a pointer to an FTSENT structure describing the first entry in a NULL-terminated linked list of the files in the directory represented by the FTSENT structure most recently returned by fts_read(). The list is linked through the fts_link field of the FTSENT structure, and is ordered by the user-specified comparison function, if any. Repeated calls to fts_children() will recreate this linked list. ๐
As a special case, if fts_read() has not yet been called for a hierarchy, fts_children() will return a pointer to the files in the logical directory specified to fts_open() or fts_open_b(), i.e., the arguments specified to fts_open() or fts_open_b(). Otherwise, if the FTSENT structure most recently returned by fts_read() is not a directory being visited in pre-order, or the directory does not contain any files, fts_children() returns NULL and sets errno to zero. If an error occurs, fts_children() returns NULL and sets errno appropriately. ๐
The FTSENT structures returned by fts_children() may be overwritten after a call to fts_children(), fts_close() or fts_read() on the same file hierarchy stream.
Option may be set to the following value:
FTS_NAMEONLYโ only the names of the files are needed. The contents of all the fields in the returned linked list of structures are undefined with the exception of thefts_nameandfts_namelenfields.
๐ fts_set() ๐
The fts_set() function allows the user application to determine further processing for the file f of the stream ftsp. The fts_set() function returns 0 on success, and -1 if an error occurs. Option must be set to one of the following values:
FTS_AGAINโ re-visit the file; any file type may be re-visited. The next call tofts_read()will return the referenced file. Thefts_statandfts_infofields of the structure will be reinitialized at that time, but no other fields will have been changed. This option is meaningful only for the most recently returned file fromfts_read(). Normal use is for post-order directory visits, where it causes the directory to be re-visited (in both pre and post-order) as well as all of its descendants. ๐ฅFTS_FOLLOWโ the referenced file must be a symbolic link. If the referenced file is the one most recently returned byfts_read(), the next call tofts_read()returns the file with thefts_infoandfts_statpfields reinitialized to reflect the target of the symbolic link instead of the symbolic link itself. If the file is one of those most recently returned byfts_children(), thefts_infoandfts_statpfields of the structure, when returned byfts_read(), will reflect the target of the symbolic link instead of the symbolic link itself. In either case, if the target of the symbolic link does not exist the fields of the returned structure will be unchanged and thefts_infofield will be set toFTS_SLNONE. ๐ฎ
If the target of the link is a directory, the pre-order return, followed by the return of all of its descendants, followed by a post-order return, is done. โจ
FTS_SKIPโ no descendants of this file are visited. The file may be one of those most recently returned by eitherfts_children()orfts_read(). โญ๏ธ
๐ง fts_set_clientptr(), fts_get_clientptr() ๐ง
The fts_set_clientptr() function sets the client data pointer for the stream ftsp to clientdata. The fts_get_clientptr() function returns the client data pointer associated with ftsp. This can be used to pass per-stream data to the comparison function. ๐
For performance reasons, fts_get_clientptr() may be shadowed by a preprocessor macro. ๐
โญ fts_get_stream() โญ
The fts_get_stream() function returns the fts stream associated with the file entry f. A typical use for this would be for a comparison function to first call fts_get_stream() on one of its arguments, then call fts_get_clientptr() to obtain the client data pointer, which in turn points to information necessary to correctly order the two entries. ๐ซ
For performance reasons, fts_get_stream() may be shadowed by a preprocessor macro. ๐
๐ fts_close() ๐
The fts_close() function closes a file hierarchy stream ftsp and restores the current directory to the directory from which fts_open() or fts_open_b() was called to open ftsp. And yes, it literally puts your cwd back where it started ๐ซถ๐
๐ RETURN VALUES ๐
Okay bestie, here's the receipts on what each function hands back to you:
fts_open()andfts_open_b()โ slay on success: they give you a pointer to the shiny new fts stream. On failure?NULL. That's it, that's the vibe. ๐ญfts_read()โ returns a pointer to the next file entry on success, or if an error happens that's specifically about that file entry. When you hit the end of the file hierarchy, it returnsNULLand sets the external variableerrnoto0. On actual failure it returnsNULLand setserrnoto an appropriate non-zero value. And lowkey important: if you call it again after theFTS_STOPflag has been set, or after you already reached the end of the stream,fts_read()returnsNULLand leaveserrnocompletely untouched. No gaslighting your errno, periodt. โจfts_children()โ returns a pointer to a linked list of file entries on success. When you reach the end of the file hierarchy it returnsNULLand setserrnoto0. On failure it returnsNULLand setserrnoto an appropriate non-zero value. ๐fts_set()โ returns0on success, and-1if itsinstrargument is invalid. Invalid instruction? Not today. ๐fts_get_clientptr()โ returns the client data pointer associated with its argument, orNULLif none has been set.fts_get_stream()โ returns a pointer to the fts stream associated with its argument.fts_close()โ returns0on success, and-1if an error occurs.
๐ซถ ERRORS ๐ซถ
Yeah so sometimes things go sideways, and errno is gonna tell you all about it.
fts_open()andfts_open_b()may fail and seterrnofor any of the errors specified for the library functionsopen(2)andmalloc(3).fts_open_b()may also fail and seterrnotoENOSYSif the blocks runtime is missing. ๐ฌfts_close()may fail and seterrnofor any of the errors specified forchdir(2)andclose(2).fts_read()andfts_children()may fail and seterrnofor any of the errors specified forchdir(2),malloc(3),opendir(3),readdir(3)andstat(2).
And in addition, fts_children(), fts_open(), and fts_set() may fail and set errno as follows:
[EINVAL]โ The options were invalid, or the list was empty. ๐ฉ
๐ฆ SEE ALSO ๐ฆ
Go read these next, bestie, they're literally the whole friend group:
find(1), chdir(2), stat(2), ftw(3), qsort(3)
๐ธ HISTORY ๐ธ
The fts interface first showed up in 4.4BSD โ vintage icon behavior. ๐
The fts_get_clientptr(), fts_get_stream(), and fts_set_clientptr() functions were introduced in FreeBSD 5.0, principally to provide for alternative interfaces to the fts functionality using different data structures. (iykyk โ it's giving "we made it flexible.")
Blocks support and the FTS_COMFOLLOWDIR and FTS_NOSTAT options were added in FreeBSD 15.0 based on similar functionality in macOS. Newer era, same energy. โจ
๐ BUGS ๐
Heads up, this one's a little sneaky:
Thefts_open()function will automatically set theFTS_NOCHDIRoption if theFTS_LOGICALoption is provided, or if it cannotopen(2)the current directory.
So likeโฆ you didn't ask for FTS_NOCHDIR, but it might just show up uninvited. Not a bug you fix, just a bug you know about. ๐
๐ That's the whole page, bestie! You just read FTS(3) from the Debian crowd, dated October 6, 2025 โ go forth and traverse some file hierarchies, you absolute main character. ๐งโโ๏ธ๐๐ซถ
๐ฆ where this page comes from
- freebsd 15.1: base 15.1
- Copyright (c) 1989, 1991, 1993, 1994 The Regents of the University of California. All rights reserved
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms