views:

80

answers:

3

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 ?!

+2  A: 

Boost remove_all http://www.boost.org/doc/libs/1_31_0/libs/filesystem/doc/index.htm

Patrick
A: 
system ("rm -rf <path-to-directory>");
Brian Hooper
+3  A: 

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);
}
caf