優化CreateDirectory函式,使之可建立多層目錄
程式碼如下:
引數與CreateDirectory一模一樣
BOOL CreateDeepDirectory(LPCTSTR lpPathName, //directory name
LPSECURITY_ATTRIBUTES lpSecurityAttributes // SD
)
{
if(PathFileExists(lpPathName)) //如果目錄已存在,直接返回
{
return TRUE;
}
CString strPath = "";
char pszSrc[MAX_PATH] = {0};
strcpy(pszSrc, lpPathName);
char *ptoken = strtok(pszSrc, "\\");
while(ptoken)
{
strPath += ptoken;
strPath += "\\";
if(!PathFileExists(strPath))
{ //建立失敗時還應刪除已建立的上層目錄,此次略
if(!CreateDirectory(strPath, lpSecurityAttributes))
{
DWORD dw = GetLastError();
CString strErr;
strErr.Format("CreateDirectory Failed: %d", dw);
AfxMessageBox(strErr);
return FALSE;
}
}
ptoken = strtok(NULL, "\\");
}
return TRUE;
} 其中PathFileExists需要新增Shlwapi.h 和引入Shlwapi.lib