简介
使用Windows的API创建多层级文件夹
效果
代码
#include <windows.h>
#include <direct.h>
#include <iostream>
#include <string>
#include <sstream>
#include <vector> //创建多层级文件夹
bool CreateDir(const std::string& path)
{std::vector<std::string> paths;std::string current_dir;size_t start_pos = 0;size_t end_pos;while ((end_pos = path.find_first_of("\\/", start_pos)) != std::string::npos){current_dir = path.substr(0, end_pos);paths.emplace_back(current_dir);start_pos = end_pos + 1;}paths.emplace_back(path);paths.emplace_back(path);//第二次创建会返回“目录已存在”的错误,即创建文件夹成功!for (auto ph : paths){int num = MultiByteToWideChar(CP_ACP, 0, ph.c_str(), -1, NULL, 0);wchar_t* wide = new wchar_t[num];MultiByteToWideChar(CP_ACP, 0, ph.c_str(), -1, wide, num);std::wstring wcpath(wide);delete[] wide;CreateDirectory(wcpath.c_str(), NULL);}DWORD error = GetLastError();if (error == ERROR_ALREADY_EXISTS)//目录已存在return true; elsereturn false;
}int main()
{std::string path = "E:\\li\\123/可行\\abc";bool ret = CreateDir(path);if (ret)std::cout << path << std::endl << "创建成功!" << std::endl;std::cin.get();return 0;
}
输出:
E:\li\123/可行\abc
创建成功!