linux c/c++ 創建多級目錄

有時候應用程序中,需要創建目錄,但如果是多級目錄,直接使用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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章