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

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

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值