删除文件夹和所有文件/子目录

24 c++ file-io delete-directory

如何在C++中删除包含所有文件/子目录(递归删除)的文件夹?

Wil*_*ell 21

认真:

system( "rm -rf /path/to/directory" )
Run Code Online (Sandbox Code Playgroud)

也许更多你正在寻找的东西,但unix具体:

/* 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;
}
Run Code Online (Sandbox Code Playgroud)


ava*_*kar 15

您可以使用boost::remove_allBoost.Filesystem的.


小智 1

标准 C++ 没有提供执行此操作的方法 - 您必须使用操作系统特定的代码或跨平台库(例如 Boost)。