C/C++ 创建多级目录(转)

24 篇文章 1 订阅

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

#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;
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值