MakeSureDirectoryPathExists是一種函式,該函式的作用是檢查指定目錄是否存在,如果不存在則創建整個Dirpath所表示的整個目錄。
函式原型,參數,返回值,函式使用,
函式原型
BOOL MakeSureDirectoryPathExists(
PCSTR Dirpath
);
參數
Dirpath:要檢查的目錄名。如果是路徑不是檔案名稱,需以 '\' 結尾。
返回值
如果目錄存在,返回TRUE;如果不存在但全部路徑創建成功,返回TRUE;
如果不存在且創建失敗,返回FALSE。
函式使用
一次性建立多級目錄(用CreateDirectory只能一級一級的建立)。
如:
MakeSureDirectoryPathExists( "c:\\a\\b\\ ");
如果a資料夾不存在也可以創建成功。
這個函式並不存在於 Kernel32.dll 中,需要包含頭檔案imagehlp.h,並連結imagehlp.lib。
該函式的實現如下,以供使用和學習。
LPTSTR _tCharAlloc(UINT uSize){ return (LPTSTR)malloc(sizeof(TCHAR) * uSize);}VOID _tCharFree(LPVOID p){ free(p);}#define IMAGEAPI WINAPIBOOL IMAGEAPI MakeSureDirectoryPathExists(LPCTSTR pszDirPath){ LPTSTR p, pszDirCopy; DWORD dwAttributes; // Make a copy of the string for editing. __try { pszDirCopy = (LPTSTR)_tCharAlloc(lstrlen(pszDirPath) + 1); if (pszDirCopy == NULL) return FALSE; lstrcpy(pszDirCopy, pszDirPath); p = pszDirCopy; // If the second character in the path is "\", then this is a UNC // path, and we should skip forward until we reach the 2nd \ in the path. if ((*p == TEXT('\\')) && (*(p + 1) == TEXT('\\'))) { p++; // Skip over the first \ in the name. p++; // Skip over the second \ in the name. // Skip until we hit the first "\" (\\Server\). while (*p && *p != TEXT('\\')) { p = CharNext(p); } // Advance over it. if (*p) { p++; } // Skip until we hit the second "\" (\\Server\Share\). while (*p && *p != TEXT('\\')) { p = CharNext(p); } // Advance over it also. if (*p) { p++; } } else if (*(p + 1) == TEXT(':')) // Not a UNC. See if it's <drive>: { p++; p++; // If it exists, skip over the root specifier if (*p && (*p == TEXT('\\'))) { p++; } } while (*p) { if (*p == TEXT('\\')) { *p = TEXT('\0'); dwAttributes = GetFileAttributes(pszDirCopy); // Nothing exists with this name. Try to make the directory name and error if unable to. if (dwAttributes == 0xffffffff) { if (!CreateDirectory(pszDirCopy, NULL)) { if (GetLastError() != ERROR_ALREADY_EXISTS) { _tCharFree(pszDirCopy); return FALSE; } } } else { if ((dwAttributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY) { // Something exists with this name, but it's not a directory... Error _tCharFree(pszDirCopy); return FALSE; } } *p = TEXT('\\'); } p = CharNext(p); } } __except (EXCEPTION_EXECUTE_HANDLER) { // SetLastError(GetExceptionCode()); _tCharFree(pszDirCopy); return FALSE; } _tCharFree(pszDirCopy); return TRUE;}