您的位置:首页 > 产品设计 > UI/UE

文件和目录之stat族函数<stat | fstat | lstat | fstatat>——APUE学习笔记(2)

2015-11-19 23:08 447 查看

一. 函数原型及具体数据结构:

#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命令,此命令可以获得当前目录下的文件所有信息。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息