POSIX Filesystem Remove files recursively (nftw, not thread-safe)

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

#define _XOPEN_SOURCE 500
#include <stdlib.h>  /* for exit() */
#include <stdio.h>   /* for remove() */
#include <ftw.h>     /* for nftw() */

int unlink_cb(
    const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
    return remove(fpath);
}

int rm_rf(const char *path)
{
    return nftw(path,
                unlink_cb,
                64 /* number of simultaneously opened fds, up to OPEN_MAX */,
                FTW_DEPTH | FTW_PHYS);
}

FTW_PHYS flag means do not follow symbolic links

FTW_DEPTH flag does a post-order traversal, that is, call unlink_cb() for the directory itself after handling the contents of the directory and its subdirectories.

nftw is interrupted if callback function returns non-zero value.

Note: this method is not thread-safe , because nftw uses chdir.



Got any POSIX Question?