Win32中提供的創建目錄的API函數--CreateDirectory只能創建單層目錄,下面提供一個創建多級目錄的方法:
bool Utility::CreateMultipleDirectory(const CString& szPath)
{
CString strDir(szPath);//存放要創建的目錄字符串
//確保以'\'結尾以創建最後一個目錄
if (strDir.GetAt(strDir.GetLength()-1)!=_T('\\'))
{
strDir.AppendChar(_T('\\'));
}
std::vector<CString> vPath;//存放每一層目錄字符串
CString strTemp;//一個臨時變量,存放目錄字符串
bool bSuccess = false;//成功標誌
//遍歷要創建的字符串
for (int i=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_iterator vIter;
int ret = 0;
for (vIter = vPath.begin(); vIter != vPath.end(); vIter++)
{
//如果CreateDirectory執行成功,返回true,否則返回false
ret = CreateDirectory(*vIter, NULL);
}
// If the CreateDirectory succeeds, the return value is nonzero.
// If the CreateDirectory fails, the return value is zero.
// ERROR_ALREADY_EXISTS: The specified directory already exists.
if ( 0 != ret || (0 == ret && ERROR_ALREADY_EXISTS == GetLastError()) )
{
bSuccess = TRUE;
}
return bSuccess;
}
出處:http://www.cnblogs.com/phinecos/archive/2008/06/19/1225224.html