我需要删除临时文件夹中的所有内容。我知道我可以使用filesystem::remove_all和filesystem::remove_all_dir,但这意味着程序也会删除临时文件夹本身,这当然不是我想要的。我找不到C++的答案,所以如果你们能帮忙的话,那就太好了。
谢谢!
发布于 2019-11-27 21:38:06
std::filesystem::remove_all( path )将递归地删除path上的一个文件夹,如果path引用的是一个文件而不是目录,它将删除该文件。
所以
void deleteDirectoryContents(const std::string& dir_path)
{
for (const auto& entry : std::filesystem::directory_iterator(dir_path))
std::filesystem::remove_all(entry.path());
}发布于 2019-11-27 21:32:15
如果可以使用std::文件系统,解决方案可能如下:
#include <filesystem>
namespace fs = std::filesystem;
void delete_dir_content(const fs::path& dir_path) {
for (auto& path: fs::directory_iterator(dir_path)) {
fs::remove_all(path);
}
}发布于 2022-10-20 12:51:49
我知道这个主题被标记为Windows,但我在寻找Unix的解决方案时发现了它。下面是使用凉鞋库运行C++ 11的Unix解决方案。它基于这位律师
#include <dirent.h>
bool cleanDirectory(const std::string &path){
struct dirent *ent;
DIR *dir = opendir(path.c_str());
if (dir != NULL) {
/* remove all the files and directories within directory */
while ((ent = readdir(dir)) != NULL) {
std::remove((path + ent->d_name).c_str());
}
closedir (dir);
} else {
/* could not open directory */
return false;
}
return true;
}https://stackoverflow.com/questions/59077670
复制相似问题