Linux C/C++ 创建目录:使用 access 判断是否存在
以下是使用C语言编写的在Linux系统下创建目录的代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int main() {
const char* dirPath = "/opt/file_video_orig/A";
int dirExists = access(dirPath, F_OK); // 检查目录是否存在
if(dirExists == -1) {
// 目录不存在,则创建目录
int dirCreated = mkdir(dirPath, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH);
if(dirCreated == -1) {
printf("Failed to create directory.\n");
exit(EXIT_FAILURE);
}
printf("Directory created successfully.\n");
}
else {
printf("Directory already exists.\n");
}
return 0;
}
此代码使用 access 函数来判断目录是否存在,如果目录不存在,则使用 mkdir 函数创建新目录。创建目录时,使用了一些权限标志位来设置目录的权限。
原文地址: https://www.cveoy.top/t/topic/qdXy 著作权归作者所有。请勿转载和采集!