1. 程式人生 > >Linux高階程式設計基礎——檔案系統程式設計之檔案型別資訊

Linux高階程式設計基礎——檔案系統程式設計之檔案型別資訊

/*檔案系統程式設計之檔案型別資訊——實驗題/

//編寫程式實現以下功能:
//1.輸入檔名稱,能夠判斷檔案型別,判斷實際使用者對該檔案具有哪些存取許可權;
//2.要求打印出檔案型別資訊,inode節點編號,連結數目,使用者id,組id,檔案大小資訊;
//3.修改檔案的許可權為當前使用者讀寫,組內使用者讀寫,組外使用者無許可權。

 //此程式通過手動輸入檔名來判斷檔案型別
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

int main()
   {                             
     struct stat statname;//定義一個結構體
     char  wjname[20];
     printf ("wenjian_mingcheng: \n");
     scanf ("%s",wjname);   //手動輸入檔名,
     if (lstat(wjname,&statname) < 0)  //“lstat”獲取檔案的屬性狀態,放在statname結構體中
         perror("lstat: \n");
       else if (S_ISREG(statname.st_mode)) //判斷檔案是否是普通檔案
         printf ("this file is regular file \n");
       else if (S_ISCHR(statname.st_mode))  //判斷檔案是否是字元檔案
         printf ("this file is character special file \n");
       else if (S_ISDIR(statname.st_mode))  //判斷檔案是否是目錄檔案
         printf ("this file is directory file \n");
       else if (S_ISBLK(statname.st_mode))  //判斷檔案是否是塊檔案
         printf ("this file is block special file \n");
       else if (S_ISFIFO(statname.st_mode))  //判斷檔案是否是管道檔案
         printf ("this file is fifo file \n");
       else if (S_ISLNK(statname.st_mode))  //判斷檔案是否是符號連結檔案
         printf ("this file is symbolic link file \n");
       else if (S_ISSOCK(statname.st_mode))  //判斷檔案是否是SOCKet檔案
         printf ("this file is SOCKET file \n");      
       printf ("power is :%o \n",statname.st_mode); //輸出檔案型別
       printf ("inode is :%ld \n",statname.st_ino); //輸出檔案節點號
       printf ("linknum is :%ld \n",statname.st_nlink); //輸出檔案硬連結數目
       printf ("uid is :%d \n",statname.st_uid); //輸出檔案的使用者id
       printf ("gid is :%d \n",statname.st_gid); //輸出檔案的使用者組id
       printf ("size is :%ld \n",statname.st_size);   //輸出檔案大小
     if (access (wjname,R_OK) < 0)  //判斷對檔案是否有讀許可權
         perror("access : \n");
     else 
         printf ("user can read %s \n",wjname); 
     if (access (wjname,W_OK) < 0)   //判斷對檔案是否有寫許可權
         perror("access : \n");
     else 
         printf ("user can write %s \n",wjname);
     if (access (wjname,X_OK) < 0)   //判斷對檔案是否有執行許可權
         perror("access : \n");
     else 
         printf ("user can exit %s \n",wjname);
     if (chmod(wjname,S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|(statname.st_mode & ~ S_IRWXO)) < 0)
        perror ("chmod :");    //“chmod”更改檔案許可權,把檔案許可權改為當前使用者和組使用者可讀可寫可執行,並且設定其他使用者沒有讀寫執行許可權,
    

return 0;
   }

/* 劃重點
lstat(wjname,&statname);
chmod
*/