C++ 判断文件路径是否存在、创建文件夹、文件夹重命名
主要用C语言的判断函数_access()、创建文件夹函数_mkdir()以及重命名函数rename()
注意:由于_mkdir()函数只能基于上一级路径存在的情况下,才能创建成功,否则失败;
所以本文需要先判断给出的路径前面是否存在,不存在则创建路径,最后重命名。
头文件:
#include <direct.h>
#include <io.h>
string sFullPath = "C:\\测试11\\测试22\\测试33\\测试44";
string sNewFullPath = sFullPath.substr(0, sFullPath.find_last_of("\\") + 1) + sName;
//判断前面的路径是否存在,不存在则创建
size_t index = sFullPath.find("\\", 0);//得到第一级路径的索引
if(index > sFullPath.length()) return;
while ((index = sFullPath.find("\\", index + 1)) < sFullPath.length())
{
string tmpPath = sFullPath.substr(0, index);
if (_access(tmpPath.c_str(), 0) != 0)
{
if (_mkdir(tmpPath.c_str()) != 0) break;
}
}
//重命名文件夹
if (_access(sFullPath.c_str(), 0) == 0)
{
int ret = rename(sFullPath.c_str(), sNewFullPath.c_str());
}
else
{
int ret = _mkdir(sNewFullPath.c_str());
}
不得不说,string的find方法yyds,非常好用