您的位置:首页 > 运维架构 > Linux

linux下面递归创建目录结构

2014-07-28 17:16 309 查看
目录中的分隔符为‘/’,当存在重复的'//'时候会自动合并一个。

void mkdirs(const char *dir)
{
std::string strPath;

if (strlen(dir) == 0 || dir == nullptr)
{
printf("strlen(dir) is 0 or dir is NULL./n");
return;
}
strPath = dir;

size_t nPos = 0, nIndex = 0;
std::string strSub;
while((nPos = strPath.find('/', nIndex)) != std::string::npos)
{
strSub = strPath.substr(0, nPos);
if(!strSub.empty())
mkdir(strSub.c_str(), 0777);

nIndex = nPos + 1;

while(strPath.length() > nIndex && strPath.at(nIndex) == '/')
{
strPath.replace(nPos, 2, "/");
}

if(strPath.length() <= nIndex)
break;
}
if(strSub.compare(strPath) != 0)
mkdir(strSub.c_str(), 0777);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息