linux cc++创建目录不存在则创建使用access判断递归创建例如optfile_video_origA给出实现代码
下面是一个使用C语言和Linux系统调用函数实现创建目录的代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int create_directory(const char* path) {
struct stat st;
if (access(path, F_OK) == 0) {
// 目录已经存在
return 0;
} else {
// 目录不存在
if (stat(path, &st) != 0) {
// 获取父目录
char parent[strlen(path) + 1];
strcpy(parent, path);
char* p = strrchr(parent, '/');
if (p != NULL) {
*p = '\0';
// 递归创建父目录
create_directory(parent);
}
}
// 创建目录
if (mkdir(path, 0755) == 0) {
return 0;
} else {
return -1;
}
}
}
int main() {
const char* path = "/opt/file_video_orig/A";
if (create_directory(path) == 0) {
printf("目录创建成功\n");
} else {
printf("目录创建失败\n");
}
return 0;
}
上述代码中的create_directory函数用于递归创建目录。首先使用access函数判断目录是否存在,如果存在则直接返回成功。如果不存在,则使用stat函数获取父目录,并递归调用create_directory函数创建父目录。最后,使用mkdir函数创建目录。
在main函数中调用create_directory函数创建目录/opt/file_video_orig/A,并根据返回值判断目录创建是否成功。
请注意,在使用该代码之前,请确保具有足够的权限来创建目录
原文地址: https://www.cveoy.top/t/topic/iwvi 著作权归作者所有。请勿转载和采集!