Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

c++ - Delete folder and all files/subdirectories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Seriously:

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

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

/* Implement system( "rm -rf" ) */
    
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <sys/stat.h>
#include <ftw.h>
#include <unistd.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 *);
        (void)s;
        (void)f;
        rm_func = flag == FTW_DP ? rmdir : unlink;
        if( status = rm_func(path), status != 0 ){
                perror(path);
        } else if( getenv("VERBOSE") ){
                puts(path);
        }
        return status;
}


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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...