linux中目录操作<1>

一、目录的权限

(1)目录文件的访问权限分为三组,分别为所有者,用户,其他。每个权限组的权限位有3个,分别为读、写、执行。

  

注意:可以使用stat函数得到目录文件的状态信息。权限为在stat结构中st_mode中.

(2)测试目录的访问权限:程序得到目录文件状态信息,如果是非目录文件,那么程序退出。该程序检查目录文件的所有者用户是否具有读写和指向的权限并全额输出结果。

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <unistd.h>
 4 #include <sys/stat.h>
 5 int main(void)
 6 {
 7     struct stat buf; /* 存储文件状态信息 */
 8     if(stat("/home", &buf) == -1){ /* 得到文件状态信息 */
 9         perror("fail to stat");
10         exit(1);
11     }
12     if(!S_ISDIR(buf.st_mode)){ /* 非目录文件 */
13         printf( "this is not a directory file
");
14         exit(1);
15     }
16     if(S_IRUSR & buf.st_mode) /* 所有者用户具有读目录权限 */
17         printf("user can read the dir
");
18     if(S_IWUSR & buf.st_mode) /* 所有者用户具有写目录权限 */
19         printf("user can write the dir
");
20     if(S_IXUSR & buf.st_mode) /* 所有者用户具有执行目录权限 */
21         printf("user can through the dir
");
22     return 0;
23 }

(3)截图

二 创建一个目录

(1)函数

  mkdir(const char* pathname,mode_t mode);

(2)返回

  成功:0

  失败:-1

(3)实现创建目录

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <stdlib.h>
 4 #include <sys/stat.h>
 5 int main(void)
 6 {
 7     if(mkdir("/home/tmp", S_IRUSR | S_IWUSR | S_IXUSR) == -1){ /* 8                                                             建一个目录 */
 9         perror("fail to mkdir");
10         exit(1);
11     }
12     printf("successfully make a dir
"); /* 输出提示信息 */
13     return 0;
14 }

(4)截图

三、删除一个目录

(1)函数:int rmdir(const char*pathname)

 返回值:

  成功:1

  失败:-1

(2)实现

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <unistd.h>
 4 int main(void)
 5 {
 6     if(rmdir("/home/tmp") == -1){ /*输出一个目录 */
 7         perror("fail to rmkdir");
 8         exit(1);
 9     }
10     printf("successfully remove a dir
"); /* 输出提示信息 */
11     return 0;
12 }

(3)截图

原文地址:https://www.cnblogs.com/lanjianhappy/p/7197062.html