1. 程式人生 > >linux中目錄操作<1>

linux中目錄操作<1>

mdi err bsp 文件的 print png usr clas sys

一、目錄的權限

(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\n"); 14 exit(1); 15 }
16 if(S_IRUSR & buf.st_mode) /* 所有者用戶具有讀目錄權限 */ 17 printf("user can read the dir\n"); 18 if(S_IWUSR & buf.st_mode) /* 所有者用戶具有寫目錄權限 */ 19 printf("user can write the dir\n"); 20 if(S_IXUSR & buf.st_mode) /* 所有者用戶具有執行目錄權限 */ 21 printf("user can through the dir\n
"); 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\n"); /* 輸出提示信息 */
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\n"); /* 輸出提示信息 */
11     return 0;
12 }

(3)截圖

技術分享

技術分享

linux中目錄操作<1>