1. 程式人生 > >CreateDirectory建立多級目錄

CreateDirectory建立多級目錄

轉自:https://blog.csdn.net/whish1994/article/details/79960513

目的:實現用CreateDirectory建立多級目錄

1.引入靜態庫

#include "shlwapi.h"

#pragma comment(lib,"shlwapi.lib")

2.函式

const wchar_t* wcstrrchr(const wchar_t* str, const wchar_t wc)
{
	const wchar_t* pwc = NULL;
	for (int i=wcslen(str)-1;i>=0;i--)
	{
		if (str[i] == wc)
		{
			pwc = str + i;
			break;
		}
	}
	return pwc;
}
 
bool createMultiDir(const wchar_t* path)
{
	if (path == NULL) return false;
	const wchar_t* pwcStrrchr = wcstrrchr(path,L'\\');
	if (!pwcStrrchr) return false;
	if (PathIsDirectory(path)) return true;
 
	wchar_t wsSubPath[MAX_PATH] = {};
	memset(wsSubPath,0,sizeof(wsSubPath));
	for (int i=0; i<pwcStrrchr-path; i++)
		wsSubPath[i] = *(path+i);
	createMultiDir(wsSubPath);
	if(CreateDirectory(path,NULL)) return true;
	return false;
}

3.呼叫案例

createMultiDir(L"d:\\whish\\test\\好孩子\\寶馬\\測試.txt"); //絕對路徑
createMultiDir(L".\\whish\\test\\好孩子\\寶馬\\測試.txt");//相對路徑

4.直接建立多級目錄下的資料夾用下面程式碼即可

SHCreateDirectoryEx(NULL, pwchar, NULL);