C/C++检测路径是否存在并创建

功能:根据传入的文件路径进行检测,对于不存在的路径进行创建,可兼容带有文件名和不带文件名的情况

 如:D:/1/2/3/test.jpg和D:/1/2/3

#include "stdafx.h"
#include 
#include "direct.h"
#include   

using namespace std;

string& replace_all(string& str, const string& old_value, const string& new_value)
{
	string::size_type  pos(0);
	while (true)
	{
		if ((pos = str.find(old_value, pos)) != string::npos)
		{
			str.replace(pos, old_value.length(), new_value);
		}
		else
		{
			break;
		}
	}

	return  str;
}

bool CreateFolder(string strSrcFilePath)
{
	string strFilePath = replace_all(strSrcFilePath, "/", "\\");
	string::size_type rFirstPos = strFilePath.rfind("\\");
	if (strFilePath.size() != (rFirstPos + 1))   /* 如果转换后的路径不是以\\结束时候,往末尾添加\\,处理的格式统一为D:\\1\\2\\3\\ */
	{
		//检测最后一个是否为文件名
		string strTemp = strFilePath.substr(rFirstPos, strFilePath.size());
		if (string::npos != strTemp.find("."))
		{
			//最后一个不是文件夹名
			strFilePath = strFilePath.substr(0, rFirstPos + 1);
		}
		else
		{
			//最后一个是文件夹名字
			strFilePath += "\\";
		}
	}
	else
	{
		strFilePath += "\\";
	}

	string::size_type startPos(0);
	string::size_type endPos(0);

	while (true)
	{
		if ((endPos = strFilePath.find("\\", startPos)) != string::npos)
		{
			string strFolderPath = strFilePath.substr(0, endPos);
			startPos = endPos + string::size_type(1);

			if (strFolderPath.rfind(":") == (strFolderPath.size() - 1))
			{
				//跳过只有系统盘的路径的情况,如:D:
				continue;
			}

			struct _stat fileStat = { 0 };
			if (_stat(strFolderPath.c_str(), &fileStat) == 0)
			{
				//文件存在,判断其为目录还是文件
				if (!(fileStat.st_mode & _S_IFDIR))
				{
					//不是文件夹,则创建失败退出返回
					return false;
				}
			}
			else
			{
				//文件夹不存在,则进行创建
				if (-1 == _mkdir(strFolderPath.c_str()))
				{
					return false;
				}
			}

			continue;
		}

		break;
	}
	return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
	//string str = "D:/1/2/3/";
	//string str = "D:/1/2/3";
	//string str = "D:\\1\\2\\3";
	//string str = "D:\\1\\2\\3\\";
	string str = ".\\..\\1\\2\\3";
	CreateFolder(str);

	return 0;
}

你可能感兴趣的:(C++)