#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
.