C/C++建立多级目录

C运行时库提供的建立目录的函数_mkdir(),在上级目录不存在时会建立失败。因此本身实现了一下建立多级目录,不管上级目录是否存在。ios

#include<iostream>
#include<vector>
#include<io.h>
#include<list>
#include<direct.h>

using namespace std;

//获得文件路径的目录
string GetPathDir(string filePath)
{
    string dirPath = filePath;
    size_t p = filePath.find_last_of('\\');
    if (p != -1)
    {
        dirPath.erase(p);
    }
    return dirPath;
}

//建立多级目录
void CreateMultiLevel(string dir)
{
    if (_access(dir.c_str(), 00) == 0)
    {
        return;
    }

    list <string> dirList;
    dirList.push_front(dir);

    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());
    }
}

int main()
{   
    string dir = "C:\\a\\b\\c\\d";
    CreateMultiLevel(dir);

    return 0;
}
相关文章
相关标签/搜索