前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C/C++创建多级目录

C/C++创建多级目录

作者头像
charlee44
发布2019-08-13 10:49:49
3.5K0
发布2019-08-13 10:49:49
举报
文章被收录于专栏:代码编写世界代码编写世界

C运行时库提供的创建目录的函数_mkdir(),在上级目录不存在时会创建失败。所以自己实现了一下创建多级目录,无论上级目录是否存在。

代码语言:javascript
复制
#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;
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-05-03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档