Linux 獲取文件屬性


使用stat/lstat獲取文件屬性

頭文件:#include <sys/types.h>

    #include <sys/stat.h>

int stat(const char  *path,struct  stat *struct_stat); int lstat(const char *path,struct stat *struct_stat);

stat與lstat的區別:這兩個方法區別在於stat沒有處理字符鏈接(軟鏈接)的能力,如果一個文件是符號鏈接,stat會直接返回它所
指向的文件的屬性;而lstat返回的就是這個符號鏈接的內容。

兩個函數的第一個參數都是文件的路徑,第二個參數是struct stat的指針。返回值為0,表示成功執行。

error:
執行失敗是,error被自動設置為下面的值:

EBADF:   文件描述詞無效
EFAULT:   地址空間不可訪問
ELOOP:   遍歷路徑時遇到太多的符號連接
ENAMETOOLONG:文件路徑名太長
ENOENT:  路徑名的部分組件不存在,或路徑名是空字串
ENOMEM:  內存不足
ENOTDIR:  路徑名的部分組件不是目錄

 

當然除了以上方法,也可以通過文件描述符來獲取文件的屬性;

 

int fstat(int fdp, struct stat *struct_stat); //通過文件描述符獲取文件對應的屬性。fdp為文件描述符

 

struct stat:

一個關於文件屬性重要的結構體

struct stat { mode_t st_mode; //文件對應的模式,文件,目錄等
ino_t st_ino; //inode節點號
dev_t st_dev; //設備號碼
dev_t st_rdev; //特殊設備號碼
nlink_t st_nlink; //文件的硬鏈接數連接數
uid_t st_uid; //文件所有者
gid_t st_gid; //文件所有者對應的組
off_t st_size; //普通文件,對應的文件字節數
time_t st_atime; //文件最后被訪問的時間
time_t st_mtime; //文件內容最后被修改的時間
time_t st_ctime; //文件屬性inode改變時間
blksize_t st_blksize; //文件內容對應的塊大小
blkcnt_t st_blocks; //文件內容對應的塊數量
};

 

stat結構體中的 st_mode 則定義了下列數種情況:

S_IFMT 0170000    文件類型的位遮罩 S_IFLNK 0120000   符號連接 S_IFREG 0100000   一般文件 S_IFBLK 0060000   區塊裝置 S_IFDIR 0040000   目錄 S_IFCHR 0020000   字符裝置 S_IFIFO 0010000 先進先出 S_ISUID 04000   文件的(set user‐id on execution)位 S_ISGID 02000   文件的(set group‐id on execution)位 S_ISVTX 01000   文件的sticky位 S_IRUSR 00400   文件所有者具可讀取權限 S_IWUSR 00200   文件所有者具可寫入權限 S_IXUSR 00100   文件所有者具可執行權限 S_IRGRP 00040   用戶組具可讀取權限 S_IWGRP 00020   用戶組具可寫入權限 S_IXGRP 00010   用戶組具可執行權限 S_IROTH 00004   其他用戶具可讀取權限 S_IWOTH 00002   其他用戶具可寫入權限 S_IXOTH 00001   其他用戶具可執行權限

 

上述的文件類型在POSIX中定義了檢查這些類型的宏定義
例如:
S_ISLNK (st_mode) 判斷是否為符號連接
S_ISREG (st_mode) 是否為一般文件
S_ISDIR (st_mode) 是否為目錄
S_ISCHR (st_mode) 是否為字符設備文件
S_ISSOCK (st_mode) 是否為socket

文件屬性獲取

 

#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> int main(int argc,char **argv) { struct stat statbuff; if(argc<2) { printf("usage: %s [filename]",argv[0]); return -1; } lstat(argv[1],&statbuff); if(S_ISLNK(statbuff.st_mode)) printf("%s is a link file\n",argv[1]); /* * //也可以這么寫 if(S_IFLNK == statbuff.st_mode & S_IFMT) printf("%s is link file\n",argv[1]); */ if(S_ISREG(statbuff.st_mode)) printf("%s is regular file\n",argv[1]); if(S_ISDIR(statbuff.st_mode)) printf("%s is directory file\n",argv[1]); return 0; }

 

 

#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> 

int main(int argc, char** argv) {   struct stat buf;   if(argc < 2)   {   printf("Usage: stat [filename]\n");   return1;   }
  if(stat(argv[
1], &buf) == ‐1)   {     perror("stat");     return1;   }
  printf(
"access time %s\n", ctime(&buf.st_atime));   printf("modify time %s\n", ctime(&buf.st_mtime));   printf("change inode time %s\n", ctime(&buf.st_ctime));   return 0; }
 
char *ctime(const time_t *timep); //將時間轉換成字符串

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM