Delete folder and all files/subdirectories

守給你的承諾、 提交于 2019-11-27 03:14:37

问题


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


回答1:


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;
}



回答2:


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




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/1149764/delete-folder-and-all-files-subdirectories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!