stat 函式解析

2021-08-15 14:29:30 字數 1638 閱讀 4621

stat 函式是用來獲取檔案的各種屬性的乙個linux下的常用api函式。

函式原型為int stat(const char* path,struct stat* buf);

stat定義如下:

struct stat ;
st_mode 的定義 –16位整數

0-2--其他人許可權(8進製)

s_iroth 00004 讀許可權

s_iwoth 00002 寫許可權

s_ixoth 00001 執行許可權

s_irwxo 00007 掩碼

3-5--所屬組許可權

s_irgrp 00040 讀許可權

s_iwgrp 00020 寫許可權

s_ixgrp 00010 執行許可權

s_irwxg 00070 掩碼

6-8--檔案所有者許可權

s_irusr 00400 讀許可權

s_iwusr 00200 寫許可權

s_ixusr 00100 執行許可權

s_irwxu 00700 掩碼

12-15--檔案型別

s_ifsock 0140000 套接字

s_iflnk 0120000 符號鏈結(軟連線)

s_ifreg 0100000 普通檔案

s_ifblk 0060000 塊裝置

s_ifdir 0040000 目錄

s_ifchr 0020000 字元裝置

s_ififo 0010000 管道

s_ifmt 掩碼,用來過濾檔案型別

statdemo.c

#include #include #include #include #include #include #include #include int main(int argc,char* argv)

if(stat(argv[1],&st) == -1)

printf("主裝置號為:%lx,次裝置號為%lx\n",(long) major(st.st_dev)),(long) minor(st.st_dev);

printf("檔案型別為:");

switch(st.st_mode & s_ifmt)

printf("節點號為 %ld\n", (long) st.st_ino);

printf("檔案許可權為: %lo (octal)\n",(unsigned long) st.st_mode);

printf("鏈結數為: %ld\n", (long) st.st_nlink);

printf("所有者: 使用者為:%s, 組為:%s\n",getpwuid(st.st_uid)->pw_name,getgrgid(st.st_gid)->gr_name);

printf("i/o快取區大小為:%ld",(long) st.st_blksize);

printf("檔案大小為:%lld 位元組\n",(long long) st.st_size);

printf("塊數為:%lld位元組\n",(long long) st.st_blocks);

return 0;

}

stat函式與stat結構體

在linux中,可以利用stat 函式來獲取乙個檔案的狀態 include include int stat const char file name,struct stat buf 這個函式執行成功返回0,失敗返回 1。取得的檔案狀態存放在buf指標指向的struct stat結構提中,struc...

stat 函式詳解

stat函式作用 獲取檔案資訊 標頭檔案 include include include 函式原型 int stat const char path,struct stat buf 返回值 成功返回0,失敗返回 1 引數 檔案路徑 名 struct stat 型別的結構體struct stat 結構...

stat函式的用法

stat函式的用法 標頭檔案 include 函式定義 int stat const char file name,struct stat buf 函式說明 通過檔名filename獲取檔案資訊,並儲存在buf所指的結構體stat中 返回值 執行成功則返回0,失敗返回 1,錯誤 存於errno 需要...