//解析字符串,逐层创建目录。使用stat函数判断目录是否存在 ,使用mkdir函数创建目录
#include "stdafx.h"
#include <stdio.h>
#include "assert.h"
#pragma warning(disable:4996)
//创建目录
static bool createDirectory(const wchar_t *pathName)
{
assert(pathName&&pathName[0]);
if (!pathName) return false;
return _wmkdir(pathName) == 0;
}
//判断目录是否存在
static bool isDirectory(const wchar_t *pathName)
{
assert(pathName&&pathName[0]);
if (!pathName) return false;
struct __stat64 buf;
if (_wstat64(pathName , &buf) != 0)
{
return false;
}
return (buf.st_mode&_S_IFDIR) != 0;
}
//创建多级目录(文件夹)
static bool makeFolder(const wchar_t *pathName)
{
assert(pathName&&pathName[0]);
if (!pathName || !pathName[0]) return false;
wchar_t buf[1024];
const wchar_t * p = pathName;
for (; *p != NULL; p++)
{
if (*p == L'/' || *p == L'\\')
{
if (p > pathName)
{
wcsncpy(buf , pathName , p - pathName);
buf[p - pathName] = 0;
if (!isDirectory(buf))
{
if (!createDirectory(buf))
return false;
}
}
}
}//for (; *p != NULL; p++)
if (p > pathName && *(p - 1) != L'/' && *(p - 1) != L'\\')
{
if (!isDirectory(pathName))
{
if (!createDirectory(pathName))
return false;
}
}
return true;
}
//测试
int main()
{
makeFolder(L"dira\\b\\c\\d");
makeFolder(L"dirb\\b\\c\\d/");
makeFolder(L"dirc/b/c/d/");
return 0;
}