c/c++ 创建多级目录

 

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。若侵权,告知即删。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值