ftw.h - Linux


Overview

ftw.h provides a high-level interface for iterating over files and directories in a directory hierarchy. It provides a simple and efficient way to process a tree of files and directories without having to worry about the intricacies of directory traversal.

Syntax

#include <ftw.h>

int ftw(const char *dirpath, int (*fn)(const char *, const struct stat *, int, struct FTW *), int ftwflags);

Options/Flags

ftwflags can take the following values:

  • FTW_F: Visit files only.
  • FTW_D: Visit directories only.
  • FTW_DNR: Don’t visit directories.
  • FTW_DP: Visit directories in post-order.
  • FTW_DEPTH: Visit files and directories in the same order they are encountered.
  • FTW_MOUNT: Stop when encountering a mount point.
  • FTW_PHYS: Follow symbolic links as if they are directories.

Examples

Example 1: Print the names of all files in a directory

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

int print_file(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
    if (typeflag == FTW_F)
        printf("%s\n", fpath);
    return 0;
}

int main()
{
    ftw(".", print_file, FTW_F);
    return 0;
}

Example 2: Count the number of files in a directory

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

int count_files(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
    if (typeflag == FTW_F)
        count++;
    return 0;
}

int main()
{
    int count = 0;
    ftw(".", count_files, FTW_F);
    printf("Total files: %d\n", count);
    return 0;
}

Common Issues

  • ftw() can be slow on large directory trees.
  • Symbolic links can cause unexpected behavior if FTW_PHYS is not used.
  • ftw() will not visit directories that are not readable by the user.

Integration

ftw() can be combined with other commands or tools for advanced tasks. For example:

  • Use ftw() to find and delete all files with a certain extension.
  • Use ftw() to create a list of all files and directories in a directory tree.
  • Use ftw() to find and replace text in all files in a directory tree.

Related Commands

  • find – Search for files and directories.
  • xargs – Execute a command on multiple arguments.