How can I delete a folder using C++?
If no cross-platform way exists, then how to do it for the most-popular OSes - Windows, Linux, Mac, iOS, Android? Would a POSIX
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
std::filesystem::remove("myEmptyDirectoryOrFile"); // Deletes empty directories or single files.
std::filesystem::remove_all("myDirectory"); // Deletes one or more files recursively.
C++14:
#include
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().