I am writing a c++ program on Linux (Ubuntu). I would like to delete the contents of a directory. It can be loose files or sub-directories.
Essentially, i would like to do something equivalent to
rm -rf <path-to-directory>/*
Can you suggest the best way of doing this in c++ along with the required headers. Is it possible to do this with sys/stat.h or sys/types.h or sys/dir.h ?!
Use the nftw()
(File Tree Walk) function, with the FTW_DEPTH
flag. Provide a callback that just calls remove()
on the passed file:
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <ftw.h>
#include <unistd.h>
int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
int rv = remove(fpath);
if (rv)
perror(fpath);
return rv;
}
int rmrf(char *path)
{
return nftw(path, unlink_cb, 64, FTW_DEPTH | FTW_PHYS);
}
If you don't want to remove the base directory itself, change the unlink_cb()
function to check the level:
int unlink_cb(const char *fpath, const struct stat *sb, int typeflag, struct FTW *ftwbuf)
{
int rv;
if (ftwbuf->level == 0)
return 0;
rv = remove(fpath);
if (rv)
perror(fpath);
return rv;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With