转载:https://blog.youkuaiyun.com/weixin_44705391/article/details/115945654
一、创建目录
1.1 direct.h 头文件
int mkdir(const char *path,mode_t mode);
函数名: mkdir
功 能: 建立一个目录
用 法: int mkdir( const char *dirname );
头文件库:direct.h
返回值:创建一个目录,若成功则返回0,否则返回-1
1.2 Linux下mkdir函数
头文件库:
#include <sys/stat.h>
#include <sys/types.h>
函数原型: int mkdir(const char *pathname, mode_t mode);
函数说明: mkdir()函数以mode方式创建一个以参数pathname命名的目录,mode定义新创建目录的权限。
返回值: 若目录创建成功,则返回0;否则返回-1,并将错误记录到全局变量errno中。
mode方式:
S_IRWXU 00700权限,代表该文件所有者拥有读,写和执行操作的权限
S_IRUSR(S_IREAD) 00400权限,代表该文件所有者拥有可读的权限
S_IWUSR(S_IWRITE) 00200权限,代表该文件所有者拥有可写的权限
S_IXUSR(S_IEXEC) 00100权限,代表该文件所有者拥有执行的权限
S_IRWXG 00070权限,代表该文件用户组拥有读,写和执行操作的权限
S_IRGRP 00040权限,代表该文件用户组拥有可读的权限
S_IWGRP 00020权限,代表该文件用户组拥有可写的权限
S_IXGRP 00010权限,代表该文件用户组拥有执行的权限
S_IRWXO 00007权限,代表其他用户拥有读,写和执行操作的权限
S_IROTH 00004权限,代表其他用户拥有可读的权限
S_IWOTH 00002权限,代表其他用户拥有可写的权限
S_IXOTH 00001权限,代表其他用户拥有执行的权限
1 用 int access(const char *pathname, int mode); 判断有没有此文件或目录 --它区别不出这是文件还是目录
2 用 int stat(const char *file_name, struct stat *buf); 判断该文件或目录是否否存在 ;得到st_mode,然后判断是不是目录文件。
stat()系统调用看是否成功,不成功就不存在,成功判断返回的st_mode是否是一个文件夹。
1.3 linux c关于目录是否存在,新建目录等操作
创建目录
#include <sys/stat.h>
#include <sys/types.h>
int mkdir(const char *pathname, mode_t mode);
运用条件:只能在已存在的目录下建立一级子目录
返回值: 返回0表示成功,返回-1表述出错。
mode 表示新目录的权限,可以取以下值:
其中,mode就用0777,0755这种形式。
判断一个目录是否存在
可以使用opendir来判断,这是比较简单的办法。
#include <sys/types.h>
#include <dirent.h>
DIR *opendir(const char *name);
The opendir() function opens a directory stream corresponding to the directory name, and returns a pointer to the directory
stream. The stream is positioned at the first entry in the directory.
代码
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include
int main()
{
if(NULL==opendir("/d1/liujian/readdb/adTest/data/html"))
mkdir("/d1/liujian/readdb/adTest/data/html",0775);
return 0;
}