[ACCEPTED]-Delete folder and all files/subdirectories-delete-directory
Seriously:
system("rm -rf /path/to/directory")
Perhaps more what you're looking 1 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;
}
You can use ftw()
, nftw()
, readdir()
, readdir_r()
to traverse a directory 4 and delete files recursively.
But since 3 neither ftw()
, nftw()
, readdir()
is thread-safe, I'll recommend 2 readdir_r()
instead if your program runs in a multi-threaded 1 environment.
Since C++17 the prefered answer to this 3 would be to use
std::filesystem::remove_all(const std::filesystem::path& folder)
which deletes the content 2 of the folder recursively and then finally 1 deletes the folder, according to this.
Standard C++ provides no means of doing 3 this - you will have to use operating system 2 specific code or a cross-platform library 1 such as Boost.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.