首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++删除所有文件和子文件夹,但保留目录本身

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

Stack Overflow用户
提问于 2019-11-27 19:59:54
回答 3查看 12.7K关注 0票数 5

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

谢谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-11-27 21:38:06

std::filesystem::remove_all( path )将递归地删除path上的一个文件夹,如果path引用的是一个文件而不是目录,它将删除该文件。

所以

代码语言:javascript
复制
void deleteDirectoryContents(const std::string& dir_path)
{
    for (const auto& entry : std::filesystem::directory_iterator(dir_path)) 
        std::filesystem::remove_all(entry.path());
}
票数 11
EN

Stack Overflow用户

发布于 2019-11-27 21:32:15

如果可以使用std::文件系统,解决方案可能如下:

代码语言:javascript
复制
#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);
    }
}
票数 6
EN

Stack Overflow用户

发布于 2022-10-20 12:51:49

我知道这个主题被标记为Windows,但我在寻找Unix的解决方案时发现了它。下面是使用凉鞋库运行C++ 11的Unix解决方案。它基于这位律师

代码语言:javascript
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59077670

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档