diff --git a/common/FileUtil.cpp b/common/FileUtil.cpp index 8973d72b27..078379ba5f 100644 --- a/common/FileUtil.cpp +++ b/common/FileUtil.cpp @@ -10,6 +10,7 @@ #include "FileUtil.hpp" #include "config.h" +#include #include #include @@ -114,6 +115,44 @@ namespace FileUtil } } + static int nftw_cb(const char *fpath, const struct stat*, int type, struct FTW*) + { + if (type == FTW_DP) + { + rmdir(fpath); + } + else if (type == FTW_F || type == FTW_SL) + { + unlink(fpath); + } + + // Always continue even when things go wrong. + return 0; + } + + void removeFile(const std::string& path, const bool recursive) + { + try + { + struct stat sb; + if (!recursive || stat(path.c_str(), &sb) == -1 || S_ISREG(sb.st_mode)) + { + // Non-recursive directories, and files. + Poco::File(path).remove(recursive); + } + else + { + // Directories only. + nftw(path.c_str(), nftw_cb, 128, FTW_DEPTH | FTW_PHYS); + } + } + catch (const std::exception&) + { + // Already removed or we don't care about failures. + } + } + + } // namespace FileUtil namespace diff --git a/common/FileUtil.hpp b/common/FileUtil.hpp index c8e7a3f870..0a172b98a2 100644 --- a/common/FileUtil.hpp +++ b/common/FileUtil.hpp @@ -63,17 +63,7 @@ namespace FileUtil /// Supresses exception when the file is already removed. /// This can happen when there is a race (unavoidable) or when /// we don't care to check before we remove (when no race exists). - inline void removeFile(const std::string& path, const bool recursive = false) - { - try - { - Poco::File(path).remove(recursive); - } - catch (const std::exception&) - { - // Already removed or we don't care about failures. - } - } + void removeFile(const std::string& path, const bool recursive = false); inline void removeFile(const Poco::Path& path, const bool recursive = false) {