#include <Windows.h> #include <stdio.h> #include <string> #include <stack> int main(int argc, char *argv[]) { std::string strPath = argv[1]; bool bIsExistDir = false; std::string strFilePath = strPath; std::stack<std::string> stackStrPath; size_t posiLastSlash = strFilePath.find_last_of("//"); // 检查路径是否是这种形式:C:/root/dir01/dir02/ (以“/”结尾) std::string strAfterLastSlash = strPath.substr(posiLastSlash + 1); std::string strBeforeLastSlash = strFilePath.substr(0, posiLastSlash); // 是以“/”结尾,那么路径取最后那个“/”之前的字符串 if (strAfterLastSlash == "") { strFilePath = strBeforeLastSlash; } stackStrPath.push(strFilePath); ; WIN32_FIND_DATA findFileData; HANDLE hFind; while (!bIsExistDir) { hFind = FindFirstFile(strFilePath.c_str(), &findFileData); // 指定的目录已经存在,则不用遍历创建 if (findFileData.dwFileAttributes == FILE_ATTRIBUTE_DIRECTORY) { bIsExistDir = true; } else { posiLastSlash = strFilePath.find_last_of("//"); size_t posiFirstSlash = strFilePath.find_first_of("//"); if (posiFirstSlash == posiLastSlash) { bIsExistDir = true; break; } strBeforeLastSlash = strFilePath.substr(0, posiLastSlash); stackStrPath.push(strBeforeLastSlash); strFilePath = strBeforeLastSlash; } } for (std::stack<std::string>::size_type idx = stackStrPath.size(); idx != 0; --idx) { std::string strNewDir = stackStrPath.top(); if (CreateDirectory(strNewDir.c_str(), NULL)) { printf ("CreateDirectory succeed! %s/n", strNewDir.c_str()); } stackStrPath.pop(); } return 1; }