Delete folder and all files/subdirectories

后端 未结 5 2075
梦谈多话
梦谈多话 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:49

    Seriously:

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

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

    /* Implement system( "rm -rf" ) */
    
    #include 
    #include 
    #include 
    #include 
    #include 
    
    
    /* 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;
    }
    

提交回复
热议问题