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