一. 函數原型及具體數據結構:
#include <sys/stat.h>
int stat(const char *retrict pathname, struct stat *restrict buf);
int fstat(int fd, struct stat *buf);
int lstat(const char *restrict pathname, struct stat *restrict buf);
int fstatat(int dirfd, const char *restrict pathname, struct stat *restrict buf, int flag);
所有四個函數返回值:成功返回0,出錯返回-1.
其中buf指針爲結構體指針,其結構如下:
struct stat {
dev_t st_dev; /* device number (file system) */
dev_t st_rdev; /* device number for special files */
ino_t st_ino; /* inode number (serial number)*/
mode_t st_mode; /* file type & mode (permissions) */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
off_t st_size; /* size in bytes, for regular files */
blksize_t st_blksize; /* best IO block size*/
blkcnt_t st_blocks; /* number of 512B blocks allocated */
struct timespec st_atime; /* time of last access */
struct timespec st_mtime; /* time of last modification */
struct timespec st_ctime; /* time of last status change */
};
結構體中的結構體成員timespce分別包含以秒和納秒爲單位定義的時間,timespec提供更高的時間戳,結構如下:
struct timespec{
time_t tv_sec ;
long tv_nsec;
};
二. stat族函數各自用途:
a.stat函數能根據pathname得到以此name命名的文件的信息結構。
b.lstat能夠根據pathname得到以此name命名的連接文件的信息結構。
–> 注意:lstat列出的是符號連接文件本身,而不是連接引用的文件。
–> 用途:需要以降序遍歷目錄層次結構時。
c.fstatat根據文件描述符得到相應文件的信息結構。
d.fstatat函數操作的函數爲:由fd參數指向的相對於當前打開目錄的路徑名,返回文件統計信息。
參數:
(1). dirfd: 如果該參數被設置爲AT_FDCWD時有以下兩種情況:
–> 當pathname爲相對路徑時:fstatat會自己計算pathname相對於但當前目錄的參數。
–> 當pathname爲絕對路徑時:dirfd參數會被丟棄。
(2). flag:該參數控制着是否跟隨着一個符號連接,如下:
–> flag默認情況下,fstata函數返回符號連接指向的實際文件信息。
–> 當AT_SYMLINK_NOFOLLOW標誌被設置,fstata不跟隨符號連接,而回返回符號連接本身信息。
強大的fstatat:
fstatat函數通過改變flag參數的值,可以分別實現其餘stat族函數的功能。
三. 實際應用:
stat族函數使用最多的地方可能就是ls -l命令,此命令可以獲得當前目錄下的文件所有信息。