Linux學習筆記2 stat與獲取檔案型別

2021-07-24 19:56:37 字數 2347 閱讀 9624

乙個檔案的常用資訊,包括:許可權、檔案型別、檔案所有者、檔案大小、檔案改動時間等資訊都儲存在乙個結構體中,即struct stat。

這個結構體定義在stat.h標頭檔案中。

基本形式如下:

struct stat ;

系統中的具體實現可能與之略有出入。比如我的電腦上,其實際的實現為:

struct stat ;

#includeint stat(const char *path, struct stat *struct_stat);

int fstat(int fd, struct stat *buf);

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

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

這4個函式可用於獲取該結構體。stat和lstat的區別在於對符號鏈結的處理。lstat返回該符號鏈結的有關資訊,而不是該符號鏈結所引用的檔案的資訊。

以上4個函式,執行成功時返回0,執行失敗時返回-1.

具體的使用方法如下:

if((lstat(path, &file_info)) < 0)

linux上常用的檔案型別包括:

檔案的型別資訊可以從stat結構體的st_mode成員中獲取。st_mode成員一般是乙個32位的整型,其13到16這4位代表的是檔案型別資訊。

可用現成的巨集定義判斷檔案型別:

s_isreg()      普通檔案

s_isdir() 目錄檔案

s_ischr() 字元特殊檔案

s_isblk() 塊特殊檔案

s_isfifo() 管道

s_islnk() 符號鏈結

s_issock() 套接字

其在標頭檔案中的具體實現如下:

#define s_islnk(m)	(((m) & s_ifmt) == s_iflnk)

#define s_isreg(m) (((m) & s_ifmt) == s_ifreg)

#define s_isdir(m) (((m) & s_ifmt) == s_ifdir)

#define s_ischr(m) (((m) & s_ifmt) == s_ifchr)

#define s_isblk(m) (((m) & s_ifmt) == s_ifblk)

#define s_isfifo(m) (((m) & s_ifmt) == s_ififo)

#define s_issock(m) (((m) & s_ifmt) == s_ifsock)

imft即為 0xf000,13到16位全1

具體的使用方法如下:

if (s_isreg(file_info.st_mode))

ptr = "regular";//普通檔案

int main(int argc, char* argv)

printf("st_mtime = %ld\n",file_info.st_mtime );

if (s_isreg(file_info.st_mode))

ptr = "regular";//普通檔案

else if(s_isdir(file_info.st_mode))

ptr = "direction";//目錄檔案

else if(s_ischr(file_info.st_mode))

ptr = "character special";//字元特殊檔案

else if(s_isblk(file_info.st_mode))

ptr = "block special"; //塊特殊檔案

else if(s_isfifo(file_info.st_mode))

ptr = "fifo";

else if(s_islnk(file_info.st_mode))

ptr = "link";

else if(s_issock(file_info.st_mode))

ptr = "sock";

else

ptr = "unknown mode";

printf("%s file\n", ptr);

}}

Linux裡stat命令與stat和lstat函式

1.stat命令,可以獲取檔案的詳細資訊 命令列輸入 stat filename 2.stat函式 標頭檔案 include include include 介面 extern int stat const char restrict file,struct stat restrict buf 引數...

Linux學習筆記(2壓縮與打包)

常用副檔名和對應程式 zcompress程式壓縮的檔案 被gzip取代 gz gzip程式壓縮的檔案 bz2 bzip2程式壓縮的檔案 壓縮比大於gzip tar tar程式打包的資料,沒有被壓縮過 tar.gz tar程式打包的資料,被gzip壓縮過 tar.bz2 tar程式打包的資料,被bzi...

linux學習筆記 2

一些常用的基本命令 uname a 檢視核心版本 ls al 顯示所有檔案的屬性 pwd 顯示當前路徑 cd 返回上一次目錄 cd 返回主目錄 date s 設定時間 日期 cal 顯示日曆 cal 2006 bc 計算器具 man info 幫助手冊 locale 顯示當前字型 locale a ...