今天操做系統上機,忽然就想把Linux C編程實戰從新看一遍,固然從文件系統着手,把my_chmod這個程序從新敲了一遍收穫很多呀。 編程
在進行程序設計時,能夠經過chmod/fchmod函數對文件訪問權限進行修改,在Shell下輸入man 2 chmod 可查看chmod/fchmod的函數原型,以下: 函數
#include <sys/stat.h> int chmod(const char *path, mode_t mode); int fchmod(int fd, mode_t mode);
chmod/fchmod的區別在於chmod以文件名做爲第一個參數,fchmod以文件描述符做爲第一個參數。參數mod主要有一下幾種組合。 學習
如下爲個人chmod函數,my_chmod.c 操作系統
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> int main(int argc,char **argv) { int mode; int mode_u; int mode_g; int mode_o; char *path; if(argc < 3){ printf("%s <mode num> <target file \n>",argv[0]); exit(0); } mode = atoi(argv[1]); if(mode > 777 || mode < 0){ printf("mode num error!\n"); exit(0); } mode_u = mode / 100; mode_g = (mode % 100) / 10; mode_o = mode % 10; mode = (mode_u * 8 * 8) + (mode_g * 8)+ mode_o; path = argv[2]; if(chmod(path,mode) == -1){ perror("chmod error"); exit(1); } return 0; }
在程序中,權限更改爲功返回0,失敗返回-1,錯誤代碼存於系統預約義變量errno中。 設計
上面的程序中,atoi這個函數調用是將字符串轉換成整型,例如:atoi("777")的返回值爲整型的777.對於chmod函數,第二個參數通常用上面列出來的宏之間取或運算。 code
對於這個程序,Linux C編程實戰中的取mode值的方法可能比較高效,附關鍵代碼: 字符串
mode_u = mode / 100; mode_g = (mode - (mode_u*100)) / 10; mode_0 = mode - (mode_u * 100) - (mode_g * 10);
這節課的學習就到這吧。(未完待續) get