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

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

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

#include "stdafx.h"
#include <string>
#include "direct.h"
#include <sys/stat.h>  

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;
}

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小佐编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值