sva*_*chu 3 c++ embedded-linux c++17
我想删除所有文件、文件夹和子文件夹,但不删除父文件夹。
所以我尝试使用带有通配符的 filesystem::remove_all ,但这似乎不起作用。
filesystem::removeall("pathtofolder/*");
Run Code Online (Sandbox Code Playgroud)
也不例外,但它不会删除任何内容。
是否不允许使用通配符?
我真的需要调用的每个文件和文件夹里面pathtofolder的removeall方法?
是否不允许使用通配符?
不存在用于支持通配符(通配符)在 std::filesystem::remove_all:
删除的内容
p(如果它是一个目录)及其所有子目录的内容,递归,然后删除p仿佛被重复应用POSIX本身remove。不遵循符号链接(符号链接被删除,而不是它的目标)
我真的需要为 pathtofolder 中的每个文件和文件夹调用 removeall 方法吗?
是的,因此您的电话应该是这样的:
#include <cstdint>
#include <exception>
#include <filesystem>
#include <iostream>
#include <system_error>
int main() {
try {
std::uintmax_t count = 0;
// loop over all the "directory_entry"'s in "pathtofolder":
for(auto& de : std::filesystem::directory_iterator("pathtofolder")) {
// returns the number of deleted entities since c++17:
count += std::filesystem::remove_all(de.path());
}
std::cout << "deleted " << count << " files and directories\n";
} catch(const std::exception& ex) {
// The overloads that does not take a std::error_code& parameter throws
// filesystem_error on underlying OS API errors, constructed with p as
// the first path argument and the OS error code as the error code
// argument.
// directory_iterator: throws if the directory doesn't exist
// remove_all: does NOT throw if the path doesn't exist
std::cerr << ex.what() << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,如果de.path()不存在,则不是OS API 错误,也不throw是异常。它将返回0已删除的文件和目录(或false在 C++17 之前)。
但是,如果不存在,directory_iterator()则会抛出一个。filesystem_errorpathtofolder