How to delete a folder in C++?
I strongly advise to use Boost.FileSystem.
http://www.boost.org/doc/libs/1_38_0/libs/filesystem/doc/index.htm
In your case that would be
boost::filesystem::remove_all(yourPath)
With C++17 you can use std::filesystem
, in C++14 std::experimental::filesystem
is already available. Both allow the usage of filesystem::remove()
.
C++17:
#include <filesystem>
std::filesystem::remove("myEmptyDirectoryOrFile"); // Deletes empty directories or single files.
std::filesystem::remove_all("myDirectory"); // Deletes one or more files recursively.
C++14:
#include <experimental/filesystem>
std::experimental::filesystem::remove("myDirectory");
Note 1:
Those functions throw filesystem_error in case of errors. If you want to avoid catching exceptions, use the overloaded variants with std::error_code
as second parameter. E.g.
std::error_code errorCode;
if (!std::filesystem::remove("myEmptyDirectoryOrFile", errorCode)) {
std::cout << errorCode.message() << std::endl;
}
Note 2:
The conversion to std::filesystem::path
happens implicit from different encodings, so you can pass strings to filesystem::remove()
.