Delete folder and all files/subdirectories

后端 未结 5 2059
梦谈多话
梦谈多话 2020-12-10 01:19

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

相关标签:
5条回答
  • 2020-12-10 01:46

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

    0 讨论(0)
  • 2020-12-10 01:49

    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;
    }
    
    0 讨论(0)
  • 2020-12-10 01:55

    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.

    0 讨论(0)
  • 2020-12-10 01:57

    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.

    0 讨论(0)
  • 2020-12-10 02:01

    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.

    0 讨论(0)
提交回复
热议问题