linux c 创建多级目录函数实现 支持绝对路径和相对路径

来源:互联网 发布:傲剑神照经数据 编辑:程序博客网 时间:2024/06/05 20:35
#include <stdio.h>#include <unistd.h>#include <string.h>#include <sys/stat.h>/** *  \function MakeDir *  \author PengWeizhe *  \date  *  \param [in] path 待创建的目录路径 可以相对路径和绝对路径 *  \return 0 创建成功 1创建失败 *  \details 创建一个目录(单级、多级) */int makeDir(const char* path){    int beginCmpPath;    int endCmpPath;    int fullPathLen;    int pathLen = strlen(path);    char currentPath[128] = {0};    char fullPath[128] = {0};    printf("path = %s\n", path);    //相对路径    if('/' != path[0])    {           //获取当前路径        getcwd(currentPath, sizeof(currentPath));        strcat(currentPath, "/");        printf("currentPath = %s\n", currentPath);        beginCmpPath = strlen(currentPath);        strcat(currentPath, path);        if(path[pathLen] != '/')        {            strcat(currentPath, "/");        }        endCmpPath = strlen(currentPath);            }    else    {        //绝对路径        int pathLen = strlen(path);        strcpy(currentPath, path);        if(path[pathLen] != '/')        {            strcat(currentPath, "/");        }        beginCmpPath = 1;        endCmpPath = strlen(currentPath);    }    //创建各级目录    for(int i = beginCmpPath; i < endCmpPath ; i++ )    {        if('/' == currentPath[i])        {            currentPath[i] = '\0';            if(access(currentPath, NULL) != 0)            {                if(mkdir(currentPath, 0755) == -1)                {                    printf("currentPath = %s\n", currentPath);                    perror("mkdir error %s\n");                    return -1;                }            }            currentPath[i] = '/';        }    }    return 0;}int main(){    makeDir("/PWZ/HJY");    makeDir("helloworld");    makeDir("/home/test.txt");    return 0;}

1 0
原创粉丝点击