C/C++创建多级目录

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

原文链接: https://www.cnblogs.com/charlee44/p/10805055.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C/C++创建多级目录

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/294618

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月15日 下午4:04
下一篇 2023年2月15日 下午4:05

相关推荐