9

I need to delete everything in my temporary folder. I know I can use filesystem::remove_all and filesystem::remove_all_dir but that would mean the program will also delete the temp folder itself which is not what I want of course. I couldn't find an answer for this that was C++ so if you guys could help, that'd be nice.

Thanks!

shook_one
  • 315
  • 1
  • 4
  • 11
  • 1
    Use a `directory_iterator` and delete the contents yourself (call `remove_all` on each member of the folder), or delete the whole thing and then recreate the folder. – Jonathan Potter Nov 27 '19 at 20:09

3 Answers3

16

std::filesystem::remove_all( path ) will recursively delete a folder at path and it will delete the file if path refers to a file not a directory.

so

void deleteDirectoryContents(const std::filesystem::path& dir)
{
    for (const auto& entry : std::filesystem::directory_iterator(dir)) 
        std::filesystem::remove_all(entry.path());
}
Jeffrey Faust
  • 547
  • 3
  • 12
jwezorek
  • 8,592
  • 1
  • 29
  • 46
7

If you can use std::filesystem, the solution could be following:

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

borievka
  • 636
  • 5
  • 13
0

I know the topic is labeled for Windows, but I found it when I was looking for the solution for Unix. So here is the solution for Unix running C++ 11 with the sandard libraries. It's based on this anwser:

#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;
}
Johann
  • 11
  • 1
  • 4