檔案管理(三)
阿新 • • 發佈:2018-12-03
編寫程式實現以下功能:
1.輸入檔名稱,能夠判斷檔案型別,判斷實際使用者對該檔案具有哪些存取許可權;
2.要求打印出檔案型別資訊,inode節點編號,連結數目,使用者id,組id,檔案大小資訊;
3.修改檔案的許可權為當前使用者讀寫,組內使用者讀寫,組外使用者無許可權。
首先,在編寫程式之前,我們需要了解如何給程式輸入檔名稱。利用scanf函式當然能夠實現,但是在C語言中,還有一個更加方便的方法能夠為程式傳遞所需引數。
在以前的學習中,我們可能認為main函式是沒有引數的,因為main的寫法是int main(),但是main函式是有且只有兩個引數的。
C語言規定main函式的引數為argc和argv。其中,argc代表引數的個數,必須為int型;argv[]儲存了函式的引數,必須為字串型別的指標陣列。因此,main函式的函式頭可以寫為:main(int argc,char *argv[])或main(int argc,char **argv)。
其中,argv[0]中儲存的是程式的全名,argv[1]為第一個引數,argv[2]為第二個引數......
接下來用一個小程式來展示一下:
#include <stdio.h>
#include <stdlib.h>
int main(int argc,char *argv[])
{
for(int i = 0; i < argc; i++)
{
printf("The argv[%d] is:%s\n ",i,argv[i]);
}
return 0;
}
程式執行結果:
通過這個小程式,能夠很清楚的看出argc和argv[]的含義。
我們可以通過argv[]檔名傳遞到程式。
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> int main(int argc,char *argv[]) { if(argc < 2) { printf("Please input the filename!\n"); return 0; } struct stat statbuf; int i; for(i = 1;i < argc;i++) { if(lstat(argv[i],&statbuf) < 0) perror("lstat"); char *buf; if(S_ISREG(statbuf.st_mode)) buf = "Regular file!"; else if(S_ISDIR(statbuf.st_mode)) buf = "Directory file!"; else if(S_ISCHR(statbuf.st_mode)) buf = "Char file!"; else buf = "Other file!"; printf("The %s is:%s\n",argv[i],buf); printf("The %s mode is:%d\n",argv[i],statbuf.st_mode); printf("The %s inode is:%d\n",argv[i],statbuf.st_ino); printf("The %s uid is:%d\n",argv[i],statbuf.st_uid); printf("The %s gid is:%d\n",argv[i],statbuf.st_gid); printf("The %s size is:%d\n",argv[i],statbuf.st_size); printf("The %s link num is:%d\n",argv[i],statbuf.st_nlink); } for(i = 1;i < argc;i++) { if(access(argv[i],R_OK)) printf("The user can read the %s\n",argv[1]); else if(access(argv[i],W_OK)) printf("The user can write the %s\n",argv[1]); else if(access(argv[i],X_OK)) printf("The user can read and write the %s\n",argv[1]); } for(i = 1;i < argc;i++) { if(chmod(argv[i],0660) < 0) perror("chmod"); else printf("The file.mode chmod successful!\n"); } return 0; }
可能有人注意到了我在修改檔案許可權時用到了0660這樣的一串數字,那麼它的含義是什麼呢?
0xxxx是檔案許可權的另一種表示方法,一般Linux檔案或目錄許可權分為三個,當前使用者,組內使用者和組外使用者。每個都有三個許可權rwx,即讀,寫,執行許可權。 許可權的表示方法有兩種,一是直觀法,即直接用rwx表示,另外一種是二進位制數值法,如:644,755等。讀是4,寫是2,執行是1,三個相加得7,以此類推,如果是6,則表示讀,寫,沒有執行許可權。
當執行程式但並沒有傳入引數時,程式退出並提示輸入檔名。
程式執行結果:
實驗完成。