diff --git a/fileop.cpp b/fileop.cpp index f656430..a99ef08 100644 --- a/fileop.cpp +++ b/fileop.cpp @@ -21,6 +21,7 @@ #include "wchar_util.h" #include "time_util.h" #include +#include #ifdef _WIN32 #if HAVE__ACCESS_S @@ -352,3 +353,38 @@ bool fileop::fclose(FILE* f) { if (!f) return false; return !::fclose(f); } + +bool fileop::mkdirs(std::string path, int mode, bool allow_exists) { + bool exists; + if (!isdir(path, exists)) return false; + if (exists) return allow_exists ? true : false; + std::string dn; +#if _WIN32 + std::string sp = "\\"; +#else + std::string sp = "/"; +#endif + dn = path; + if (!dn.length() || dn == ".") dn = "." + sp; + if (!isdir(dn, exists)) return false; + if (exists) return allow_exists ? true : false; + std::list li; + li.push_back(dn); + do { + dn = dirname(dn) + sp; + if (dn.length() == 1) { + if (li.size() > 0) { + auto en = *(li.rbegin()); + if (en == ("." + sp)) return false; + } + dn = "." + sp; + } + if (!isdir(dn, exists)) return false; + if (!exists) li.push_back(dn); + } while (!exists); + auto it = li.rbegin(); + for (; it != li.rend(); it++) { + if (!mkdir(*it, mode)) return false; + } + return true; +} diff --git a/fileop.h b/fileop.h index cdc7328..bc4e6ca 100644 --- a/fileop.h +++ b/fileop.h @@ -117,5 +117,13 @@ namespace fileop { * @return true if the stream is successfully closed */ bool fclose(FILE* f); + /** + * @brief Creates a new directory recursively. + * @param path Path for a new directory. + * @param mode Directory permission. (Linux only) + * @param allow_exists If directory is already exists return true rather than false. + * @return true if create successfully otherwise false + */ + bool mkdirs(std::string path, int mode, bool allow_exists = false); } #endif