gpt4 book ai didi

c++ 17 filesystem::remove_all 带通配符路径

转载 作者:行者123 更新时间:2023-12-01 14:35:50 34 4
gpt4 key购买 nike

我想删除所有文件、文件夹和子文件夹,但不删除父文件夹。
所以我尝试使用带有通配符的 filesystem::remove_all ,但这似乎不起作用。

filesystem::removeall("pathtofolder/*");
也不异常(exception),但它不会删除任何内容。
是否不允许使用通配符?
我真的需要调用 pathtofolder 中的每个文件和文件夹吗? removeall方法?

最佳答案

Are wildcards are not allowed?


不支持 globbing (通配符)在 std::filesystem::remove_all :

Deletes the contents of p (if it is a directory) and the contents of all its subdirectories, recursively, then deletes p itself as if by repeatedly applying the POSIX remove. Symlinks are not followed (symlink is removed, not its target)


Do I really need to call for each file and folder inside of pathtofolder the removeall method?


是的,因此您的电话应该是这样的:
#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;
}
}
请注意,如果 de.path()不存在,它不是操作系统 API 错误,也不会 throw一个异常(exception)。它将返回 0删除的文件和目录(或 C++17 之前的 false)。
然而, directory_iterator()会抛出 filesystem_error如果 pathtofolder不存在。

关于c++ 17 filesystem::remove_all 带通配符路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62693846/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com