C/C++ 建立多級資料夾(mkdir)
阿新 • • 發佈:2018-11-21
//依賴的標頭檔案 #include <direct.h> ##include <string> #include <io.h> int CreateMultiFileList(char *strDirPath) { if (strlen(strDirPath) > MAX_PATH) { return -1; } int ipathLength = strlen(strDirPath); int ileaveLength = 0; int iCreatedLength = 0; char szPathTemp[MAX_PATH] = { 0 }; for (int i = 0; (NULL != strchr(strDirPath + iCreatedLength, '\\')); i++) { ileaveLength = strlen(strchr(strDirPath + iCreatedLength, '\\')) - 1; iCreatedLength = ipathLength - ileaveLength; strncpy(szPathTemp, strDirPath, iCreatedLength); mkdir(szPathTemp); } if (iCreatedLength < ipathLength) { mkdir(strDirPath); } return 0; } int main(int argc, char *argv[]) { string strSavedpath = "E:\\1\\2\\3"; char cPath[256] = { 0 }; sprintf(cPath, "%s", strSavedpath.c_str()); CreateMultiFileList(cPath); }
======================
void CreateDir(const char *dir) { int m = 0, n; string str1, str2; str1 = dir; str2 = str1.substr(0, 2); str1 = str1.substr(3, str1.size()); while (m >= 0) { m = str1.find('\\'); str2 += '\\' + str1.substr(0, m); //判斷該目錄是否存在 n = _access(str2.c_str(), 0); if (n == -1) { //建立目錄檔案 _mkdir(str2.c_str()); } str1 = str1.substr(m + 1, str1.size()); } } int main(int argc, char *argv[]) { char dir[] = "E:\\1\\2\\3"; CreateDir(dir); }