tags:

views:

375

answers:

4

How I can delete folder with subfolders (recursive deleting) in C++?

+2  A: 

Here you go:

#include <dirent.h>
#include <string>
using std::string;

bool IsDirectory(char path[]) {
    int i = strlen(path) - 1;
    if (path[strlen(path)] == '.') {return true;} // exception for directories
    // such as \. and \..
    for(i; i >= 0; i--) {
        if (path[i] == '.') return false; // if we first encounter a . then it's a file
        else if (path[i] == '\\' || path[i] == '/') return true; // if we first encounter a \ it's a dir
    }
}

bool RemoveDirectory(string path) {
    if (path[path.length()-1] != '\\') path += "\\";
    // first off, we need to create a pointer to a directory
    DIR *pdir = NULL; // remember, it's good practice to initialise a pointer to NULL!
    pdir = opendir (path.c_str());
    struct dirent *pent = NULL;
    if (pdir == NULL) { // if pdir wasn't initialised correctly
        return false; // return false to say "we couldn't do it"
    } // end if
    char file[256];

    int counter = 1; // use this to skip the first TWO which cause an infinite loop (and eventually, stack overflow)
    while (pent = readdir (pdir)) { // while there is still something in the directory to list
        if (counter > 2) {
            for (int i = 0; i < 256; i++) file[i] = '\0';
            strcat(file, path.c_str());
            if (pent == NULL) { // if pent has not been initialised correctly
                return false; // we couldn't do it
            } // otherwise, it was initialised correctly, so let's delete the file~
            strcat(file, pent->d_name); // concatenate the strings to get the complete path
            if (IsDirectory(file) == true) {
                RemoveDirectory(file);
            } else { // it's a file, we can use remove
                remove(file);
            }
        } counter++;
    }

    // finally, let's clean up
    closedir (pdir); // close the directory
    if (!rmdir(path.c_str())) return false; // delete the directory
    return true;
}

/** EXAMPLE USAGE **/
#include <iostream>
using std::cin;
using std::cout;
int main() {
    RemoveDirectory("C:\\New Folder");
    cin.get();
    return EXIT_SUCCESS;
}

Source: http://www.dreamincode.net/code/snippet2700.htm

Zyphrax
Note this is POSIX specific code.
anon
+1  A: 

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.

anon
+8  A: 

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

avakar
+1  A: 

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

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


/* Implement system( "rm -rf" ) */

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/syslimits.h>
#include <ftw.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 * );

    switch( flag ) {
    default:     rm_func = unlink; break;
    case FTW_DP: rm_func = rmdir;
    }
    if( status = rm_func( path ), status != 0 )
     perror( path );
    else
     puts( path );
    return status;
}


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

William Pursell
Was this downvoted because it's C instead of C++ (although it compiles just fine with g++ -Wall -Wextra), or because the downvoter's platform doesn't have nftw? Comment when you downvote, please! This is solid code.
William Pursell