C++ 使用Windows的API CreateDirectory 创建多层级文件夹
  CiIZfyyIq65u 2023年11月30日 29 0


简介

使用Windows的API创建多层级文件夹

效果

C++ 使用Windows的API CreateDirectory 创建多层级文件夹_c语言

代码

#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; 
	else
		return 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
创建成功!


【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月30日 0

暂无评论

推荐阅读
CiIZfyyIq65u