mirror of
https://github.com/lifegpc/c-utils.git
synced 2026-07-08 01:30:39 +08:00
Add new function mkdirs
This commit is contained in:
36
fileop.cpp
36
fileop.cpp
@@ -21,6 +21,7 @@
|
|||||||
#include "wchar_util.h"
|
#include "wchar_util.h"
|
||||||
#include "time_util.h"
|
#include "time_util.h"
|
||||||
#include <regex>
|
#include <regex>
|
||||||
|
#include <list>
|
||||||
|
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
#if HAVE__ACCESS_S
|
#if HAVE__ACCESS_S
|
||||||
@@ -352,3 +353,38 @@ bool fileop::fclose(FILE* f) {
|
|||||||
if (!f) return false;
|
if (!f) return false;
|
||||||
return !::fclose(f);
|
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;
|
||||||
|
}
|
||||||
|
|||||||
8
fileop.h
8
fileop.h
@@ -117,5 +117,13 @@ namespace fileop {
|
|||||||
* @return true if the stream is successfully closed
|
* @return true if the stream is successfully closed
|
||||||
*/
|
*/
|
||||||
bool fclose(FILE* f);
|
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
|
#endif
|
||||||
|
|||||||
Reference in New Issue
Block a user