Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear directory contents in c++ on Linux (basically, i want to do 'rm -rf <directorypath>/*'

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

like image 945
AMM Avatar asked Jul 06 '10 07:07

AMM


1 Answers

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;
}
like image 129
caf Avatar answered Sep 27 '22 16:09

caf