Add new function mkdirs

This commit is contained in:
2021-12-29 22:51:18 +08:00
parent a66c2f4bbd
commit 4618b97a2e
2 changed files with 44 additions and 0 deletions

View File

@@ -21,6 +21,7 @@
#include "wchar_util.h"
#include "time_util.h"
#include <regex>
#include <list>
#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<std::string> 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;
}

View File

@@ -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