有時候應用程序中,需要創建目錄,但如果是多級目錄,直接使用mkdir函數是沒法實現的,需要循環調用mkdir函數, 這裏就做一個記錄,以便以後需要的時候,可以直接使用。
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
bool createDirs(const std::string& dirName)
{
uint32_t beginCmpPath = 0;
uint32_t endCmpPath = 0;
std::string fullPath = "";
LOGD("path = %s\n", dirName.c_str());
if('/' != dirName[0])
{ //Relative path
//get current path
fullPath = getcwd(nullptr, 0);
beginCmpPath = fullPath.size();
LOGD("current Path: %s\n", fullPath.c_str());
fullPath = fullPath + "/" + dirName;
}
else
{
//Absolute path
fullPath = dirName;
beginCmpPath = 1;
}
if (fullPath[fullPath.size() - 1] != '/')
{
fullPath += "/";
}
endCmpPath = fullPath.size();
//create dirs;
for(uint32_t i = beginCmpPath; i < endCmpPath ; i++ )
{
if('/' == fullPath[i])
{
std::string curPath = fullPath.substr(0, i);
if(access(curPath.c_str(), F_OK) != 0)
{
if(mkdir(curPath.c_str(), S_IRUSR|S_IRGRP|S_IROTH|S_IWUSR|S_IWGRP|S_IWOTH) == -1)
{
LOGD("mkdir(%s) failed(%s)\n", curPath.c_str(), strerror(errno));
return false;
}
}
}
}
return true;
}