C运行时库提供的创建目录的函数_mkdir(),在上级目录不存在时会创建失败。所以自己实现了一下创建多级目录,无论上级目录是否存在。
#include<io.h>
#include<direct.h>
std::string GetPathDir(std::string filePath);
void CreateMultiLevel(std::string dir);
int main() {
std::string dir = "C:\\level1\\level2\\level2\\level4";
CreateMultiLevel(dir);
return 0;
}
//得到文件路径的目录
std::string GetPathDir(std::string filePath) {
std::string dirPath = filePath;
size_t p = filePath.find_last_of('\\');
if (p != -1) {
dirPath.erase(p);
}
return dirPath;
}
//创建多级目录
void CreateMultiLevel(std::string dir) {
if (_access(dir.c_str(), 00) == 0) {
return;
}
std::list <std::string> dirList;
dirList.push_front(dir);
std::string curDir = GetPathDir(dir);
while (curDir != dir) {
if (_access(curDir.c_str(), 00) == 0) {
break;
}
dirList.push_front(curDir);
dir = curDir;
curDir = GetPathDir(dir);
}
for (auto it : dirList) {
_mkdir(it.c_str());
}
}
转自https://www.cnblogs.com/charlee44/p/10805055.html。若侵权,告知即删。