C++17 文件系统::remove_all 带有通配符路径



我想删除所有文件、文件夹和子文件夹,但不删除父文件夹。

所以我尝试使用带有通配符的文件系统::remove_all,但这似乎不起作用。

filesystem::removeall("pathtofolder/*");

没有例外,但它不会删除任何内容。

不允许使用通配符吗?

我真的需要调用pathtofolderremoveall方法中的每个文件和文件夹吗?

不允许使用通配符吗?

std::filesystem::remove_all中不支持通配符(通配符(:

归删除p的内容(如果是目录(及其所有子目录的内容,然后删除p本身,就像重复应用 POSIXremove一样。不遵循符号链接(符号链接被删除,而不是其目标(

我真的需要为 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 directoriesn";
} 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;
}
}

请注意,如果de.path()不存在,则不是操作系统 API 错误,也不会throw异常。它将返回0已删除的文件和目录(或C++17之前的false(。

但是,如果pathtofolder不存在,directory_iterator()将抛出filesystem_error

@TedLyngmo提供了一个有效的解决方案;我通常会将这些东西添加到实用程序标头中,例如,在我的src/util/filesystem.hpp中,我输入:

namespace util {
namespace filesystem {
std::uintmax_t remove_all_inside(const std::filesystem::path& dir) {
std::uintmax_t removed_items_count { 0 };
if (not is_directory(dir)) { 
throw std::invalid_argument("Not a directory: " + dir.str());
}
for(auto& dir_element : std::filesystem::directory_iterator(dir)) {
removed_items_count += std::filesystem::remove_all(dir_element .path());
}
return removed_items_count;
}
} // namespace filesystem
} // namespace util

然后我可以写:

#include <util/filesystem.hpp>
// ... etc etc ...
util::filesystem::remove_all_inside("/path/to/folder");

这种方法的一个很好的方面是它可以与早期版本的标准一起工作 - 你只需使用一些预处理器魔术来选择std::filesystem或基于C++版本boost::filesystem;但使用实用程序函数的代码保持不变。

示例:

std::wregex regExpName { LR"(^.*.tmp$)" };
const auto tmpPath { std::filesystem::temp_directory_path() };
for (const auto& element : std::filesystem::directory_iterator(tmpPath))
if (not element.is_directory() and std::regex_match(element.path().filename().wstring(), regExpName))
std::filesystem::remove(element.path());

我认为不允许使用通配符,

从文档中可以看出,std::filesystem::remove/remove_all映射到POSIX系统上的unlink/rmdir和Windows上的DeleteFileW/RemoveDirectoryW。

两者都不接受通配符。

看: 如何使用通配符删除 C 中的多个文件?

如何在 c++ 中使用带有通配符的删除文件

最新更新