Win32中提供的创建目录的API函数--CreateDirectory只能创建单层目录,下面提供一个创建多级目录的方法:
bool
Utility::CreateMultipleDirectory(
const
CString
&
szPath)
{
CStringstrDir(szPath);//存放要创建的目录字符串
//确保以'/'结尾以创建最后一个目录
if(strDir.GetAt(strDir.GetLength()-1)!=_T('//'))
{
strDir.AppendChar(_T('//'));
}
std::vector<CString>vPath;//存放每一层目录字符串
CStringstrTemp;//一个临时变量,存放目录字符串
boolbSuccess=false;//成功标志
//遍历要创建的字符串
for(inti=0;i<strDir.GetLength();++i)
{
if(strDir.GetAt(i)!=_T('//'))
{//如果当前字符不是'//'
strTemp.AppendChar(strDir.GetAt(i));
}
else
{//如果当前字符是'//'
vPath.push_back(strTemp);//将当前层的字符串添加到数组中
strTemp.AppendChar(_T('//'));
}
}
//遍历存放目录的数组,创建每层目录
std::vector<CString>::const_iteratorvIter;
for(vIter=vPath.begin();vIter!=vPath.end();vIter++)
{
//如果CreateDirectory执行成功,返回true,否则返回false
bSuccess=CreateDirectory(*vIter,NULL)?true:false;
}
returnbSuccess;
}
{
CStringstrDir(szPath);//存放要创建的目录字符串
//确保以'/'结尾以创建最后一个目录
if(strDir.GetAt(strDir.GetLength()-1)!=_T('//'))
{
strDir.AppendChar(_T('//'));
}
std::vector<CString>vPath;//存放每一层目录字符串
CStringstrTemp;//一个临时变量,存放目录字符串
boolbSuccess=false;//成功标志
//遍历要创建的字符串
for(inti=0;i<strDir.GetLength();++i)
{
if(strDir.GetAt(i)!=_T('//'))
{//如果当前字符不是'//'
strTemp.AppendChar(strDir.GetAt(i));
}
else
{//如果当前字符是'//'
vPath.push_back(strTemp);//将当前层的字符串添加到数组中
strTemp.AppendChar(_T('//'));
}
}
//遍历存放目录的数组,创建每层目录
std::vector<CString>::const_iteratorvIter;
for(vIter=vPath.begin();vIter!=vPath.end();vIter++)
{
//如果CreateDirectory执行成功,返回true,否则返回false
bSuccess=CreateDirectory(*vIter,NULL)?true:false;
}
returnbSuccess;
}