Reputation:
How can I delete a folder with all it's files/subdirectories (recursive deletion) in C++?
Upvotes: 25
Views: 32362
Reputation: 212664
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;
}
Upvotes: 23
Reputation: 5098
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.
Upvotes: 4
Reputation: 3403
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.
Upvotes: 4
Reputation:
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.
Upvotes: 1