一、主要函數應用?
#include <sys/stat.h>
int stat(const char *path, struct stat *buf);
int fstat(int fd, struct stat *buf)
int lstat(const char *path, struct stat *buf);
int fstat(int fd, const char *path, struct stat *buf, int flag);
參數:
- ?stat讀取的是連接文件指向的文件的屬性l
- stat讀取的鏈接文件本身的屬性lstat
?
二、struct stat 的結構體
struct stat
{dev_t st_dev; //文件的設備編號ino_t st_ino; //節點mode_t st_mode; //文件的類型和存取的權限nlink_t st_nlink; //連到該文件的硬連接數目,剛建立的文件值為1uid_t st_uid; //用戶IDgid_t st_gid; //組IDdev_t st_rdev; //(設備類型)若此文件為設備文件,則為其設備編號off_t st_size; //文件字節數(文件大小)blksize_t st_blksize; //塊大小(文件系統的I/O 緩沖區大小)blkcnt_t st_blocks; //塊數time_t st_atime; //最后一次訪問時間time_t st_mtime; //最后一次修改時間time_t st_ctime; //最后一次改變時間(指屬性)
};
?
三、st_mode 的結構
- 15-12 位保存文件類型
- 11-9 位保存執行文件時設置的信息
- 8-0 位保存文件訪問權限
圖1 展示了 st_mode 各個位的結構。?
四、一些常用的宏?
-st_mode -- 16位整數○ 0-2 bit -- 其他人權限
- S_IROTH 00004 讀權限
- S_IWOTH 00002 寫權限
- S_IXOTH 00001 執行權限
- S_IRWXO 00007 掩碼, 過濾 st_mode中除其他人權限以外的信息○ 3-5 bit -- 所屬組權限
- S_IRGRP 00040 讀權限
- S_IWGRP 00020 寫權限
- S_IXGRP 00010 執行權限
- S_IRWXG 00070 掩碼, 過濾 st_mode中除所屬組權限以外的信息○ 6-8 bit -- 文件所有者權限
- S_IWUSR 00200 寫權限
- S_IXUSR 00100 執行權限
- S_IRWXU 00700 掩碼, 過濾 st_mode中除文件所有者權限以外的信息○ 12-15 bit -- 文件類型
- S_IFSOCK 0140000 套接字
- S_IFLNK 0120000 符號鏈接(軟鏈接)
- S_IFBLK 0060000 塊設備
- S_IFDIR 0040000 目錄
- S_IFCHR 0020000 字符設備
- S_IFIFO 0010000 管道
- S_IFMT 0170000 掩碼,過濾 st_mode中除文件類型以外的信息(st_mode & S_IFMT) == S_IFREG
?
五、程序清單
測試代碼:
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>int main()
{struct stat st;struct stat* st1;st1 = &st;int ret = stat("english.txt", &st);if(ret == -1) {perror("stat error");exit(1);}printf("file size = %d\n", (int)st.st_size);return 0;
}
輸出結果:
?
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>int main()
{struct stat st;struct stat* st1;st1 = &st;int ret = stat("english.txt", &st);if(ret == -1) {perror("stat error");exit(1);}printf("file size = %d\n", (int)st.st_size);if(st.st_mode & S_IFMT == S_IFREG) {printf("這是一個普通文件\n");}if(st.st_mode & S_IRUSR) {printf(" R ");}if(st.st_mode & S_IWUSR) {printf(" W ");}if(st.st_mode & S_IXUSR) {printf(" X ");}printf("\n");return 0;
}
輸出結果:
?
#include <stdio.h>
#include <sys/stat.h>
#include <stdlib.h>int main()
{struct stat st;struct stat* st1;st1 = &st;int ret = lstat("s.s", &st);if(ret == -1) {perror("stat error");exit(1);}printf("file size = %d\n", (int)st.st_size);if(st.st_mode & S_IFMT == S_IFREG) {printf("這是一個普通文件\n");}if(st.st_mode & S_IRUSR) {printf(" R ");}if(st.st_mode & S_IWUSR) {printf(" W ");}if(st.st_mode & S_IXUSR) {printf(" X ");}printf("\n");return 0;
}
輸出結果:
參考資料:
1.?12-stat 函數
2.?13-stat 結構體 st_mode 字段
?