C语言实现mkdir -p递归创建目录

C语言代码实现

/**
 * 这是一个测试 递归创建目录 的程序;
 * 使用 mkdir函数而不是命令;
 * 将使用“mkdir”命令创建目录替换为使用递归函数创建目录;
*/

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <libgen.h>
#include <sys/stat.h>

// 递归创建文件夹
int create_directory(const char* path) 
{
    struct stat st;
    if (stat(path, &st) == 0)
    {
        // 检查路径是否是一个目录
        if (S_ISDIR(st.st_mode) == 1)
        {
            return 0;
        } 
        else
        {
            // 路径是一个文件,无法创建文件夹
            return -1;
        }
    }
    else
    {
        // 路径不存在,递归创建上级目录
        char* path_copy = strdup(path);
        // strdup 函数是字符串的复制函数

        char* parent_path = dirname(path_copy);
        // 使用 dirname函数 获得父目录
        
        create_directory(parent_path);
        free(path_copy);

        // 创建文件夹
        if (mkdir(path, 0777) == -1) 
        {
            return -1;
        }
        return 0;
    }
}

int main(int argc, char const *argv[])
{
    char *path = "./my_mkdir/my_mkdir/my_mkdir";

    int ret = create_directory(path);
    if (0 == ret)
    {
        printf("mkdir success\n");
    }
    else
    {
        printf("mkdir failed\n");
    }
    
    return 0;
}

  • 7
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值