25

How can I delete a folder with all it's files/subdirectories (recursive deletion) in C++?

Sam
  • 7,252
  • 16
  • 46
  • 65
  • Just a side node: There is a duplicate to this question, if you do not want to rely on boost, it is worth to have a look at the accepted answer [there](http://stackoverflow.com/a/2256974/1312382). – Aconcagua Sep 14 '15 at 10:03

5 Answers5

23

Seriously:

system("rm -rf /path/to/directory")

Perhaps more what you're looking for, but unix specific:

/* Implement system( "rm -rf" ) */
    
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/stat.h>
#include <ftw.h>
#include <unistd.h>

/* Call unlink or rmdir on the path, as appropriate. */
int
rm(const char *path, const struct stat *s, int flag, struct FTW *f)
{
        int status;
        int (*rm_func)(const char *);
        (void)s;
        (void)f;
        rm_func = flag == FTW_DP ? rmdir : unlink;
        if( status = rm_func(path), status != 0 ){
                perror(path);
        } else if( getenv("VERBOSE") ){
                puts(path);
        }
        return status;
}


int
main(int argc, char **argv)
{
        (void)argc;
        while( *++argv ) {
                if( nftw(*argv, rm, OPEN_MAX, FTW_DEPTH) ){
                        perror(*argv);
                        return EXIT_FAILURE;
                }
        }
        return EXIT_SUCCESS;
}
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • 1
    How portable is `system( "rm -rf /path/to/directory" )`? Will it work on any *nix OS? Clearly won't work in Windows. – Aaron Campbell Nov 12 '16 at 02:18
  • It might be worth using `FTW_MOUNT|FTW_PHYS|FTW_DEPTH` instead of just `FTW_DEPTH` — that avoids disasters with symlinks and mounted file systems. See [`nftw()`](http://pubs.opengroup.org/onlinepubs/9699919799/functions/nftw.html) for details. – Jonathan Leffler Apr 11 '19 at 05:40
16

You can use boost::remove_all from Boost.Filesystem.

avakar
  • 32,009
  • 9
  • 68
  • 103
4

You can use ftw(), nftw(), readdir(), readdir_r() to traverse a directory and delete files recursively.
But since neither ftw(), nftw(), readdir() is thread-safe, I'll recommend readdir_r() instead if your program runs in a multi-threaded environment.

zeekvfu
  • 3,344
  • 1
  • 22
  • 19
3

Since C++17 the prefered answer to this would be to use

std::filesystem::remove_all(const std::filesystem::path& folder)

which deletes the content of the folder recursively and then finally deletes the folder, according to this.

Exagon
  • 4,798
  • 6
  • 25
  • 53
1

Standard C++ provides no means of doing this - you will have to use operating system specific code or a cross-platform library such as Boost.