[ACCEPTED]-Delete folder and all files/subdirectories-delete-directory

Accepted answer
Score: 23


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

Perhaps more what you're looking 1 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. */
rm(const char *path, const struct stat *s, int flag, struct FTW *f)
        int status;
        int (*rm_func)(const char *);
        rm_func = flag == FTW_DP ? rmdir : unlink;
        if( status = rm_func(path), status != 0 ){
        } else if( getenv("VERBOSE") ){
        return status;

main(int argc, char **argv)
        while( *++argv ) {
                if( nftw(*argv, rm, OPEN_MAX, FTW_DEPTH) ){
                        return EXIT_FAILURE;
        return EXIT_SUCCESS;
Score: 16

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


Score: 4

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

Score: 3

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

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

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

Score: 1

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

More Related questions