C++ 删除所有文件和子文件夹,但保留目录本身。

9
我需要删除临时文件夹中的所有内容。我知道可以使用filesystem::remove_allfilesystem::remove_all_dir,但这意味着程序将删除临时文件夹本身,这当然不是我想要的。我找不到C++的解决方案,如果你们能帮忙,那就太好了。
谢谢!

1
使用 directory_iterator 并自行删除其内容(在文件夹的每个成员上调用 remove_all),或者删除整个文件夹,然后重新创建该文件夹。 - Jonathan Potter
3个回答

16

std::filesystem::remove_all( path )会递归删除位于path的文件夹,并且如果path指向的是一个文件而不是目录,则也会删除该文件。

所以

void deleteDirectoryContents(const std::filesystem::path& dir)
{
    for (const auto& entry : std::filesystem::directory_iterator(dir)) 
        std::filesystem::remove_all(entry.path());
}

7
如果您能够使用 std::filesystem,则解决方案可能如下所示:
#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);
    }
}


0

我知道这个话题被标为Windows,但我发现它当我在寻找Unix的解决方案时。因此,这里是适用于Unix运行C++ 11和标准库的解决方案。它基于this answer

#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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接