使用WIN32API,直接贴代码
bool AutoCreateDirectory(const string &strFilePath)
{
if(strFilePath.empty()) //目录名为空 无法创建
{
return false;
}
//判断目录是否存在 存在直接返回True
if(FILE_ATTRIBUTE_DIRECTORY == GetFileAttributes(strFilePath.c_str()))
{
return true;
}
string strTemp = strFilePath; //保存变量
//判断是不是以/或者\结尾 确保下面可以创建多层目录
if(strFilePath[strFilePath.length() - 1] != '/' || strFilePath[strFilePath.length() - 1] != '\\')
{
strTemp += "/";
}
string strTempPath;
for(int i = 0; i < strTemp.length(); ++i)
{
if(strTemp[i] == '/' || strTemp[i] == '\\')
{
if(!strTempPath.empty())
{
DWORD dwAttributes = GetFileAttributes(strTempPath.c_str());
DWORD dwHidden = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_HIDDEN;
if((dwAttributes == INVALID_FILE_ATTRIBUTES) ||
!((FILE_ATTRIBUTE_DIRECTORY & dwAttributes) && dwHidden != dwAttributes))
{
if(!CreateDirectory(strTempPath.c_str(), NULL))
{
DWORD dwErrCode = GetLastError();
LOG_ERROR("AutoCreateDirectory CreateDirectory failed. Path:" << strTempPath
<<" Error:" <