入门客AI创业平台(我带你入门,你带我飞行)
博文笔记

函数stat,fstat,fstatat和lstat

创建时间:2017-08-11 投稿人: 浏览次数:306
# include <sys/stat.h>
int stat(const char *restrict 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 fd, const char *restrict pathnaem, struct stat *restrict buf, int flag);
所有4个函数的返回值:若成功;返回0;若出错;返回-1

函数说明:
一旦给出pathname,stat函数将返回与此命名文件有关的信息结构。
fstat函数获得已在描述符fd上打开文件的有关信息。
lstat函数类似于stat,但当命名文件是一个符号链接时,lstat返回
该符号链接的有关信息,而不是由该符号链接引用的文件信息。

fstatat函数为一个相对于当前打开目录(由fd参数指向)的路径名返回文件统计信息。
flag参数控制着是否跟随着一个符号链接。当AT_SYMLINK_NOFOLLOW标志被设置时,
fstatat不会跟随符号链接,而是返回符号链接本身的信息。否则,在默认情况下,
返回的是符号链接所指向的实际文件信息。如果fd参数的值是AT_FDCWD,并且
pathname参数是一个相对路径名,fstatat会计算相对于当前目录的pathname参数,
如果pathname是一个绝对路径,fd参数就会被忽略。这个两种情况下,根据flag的取值,
fstatat的作用就跟stat或lstat一样。

第2个参数buf是一个指针,它指向一个我们必须提供的结构。函数来填充由buf指向的结构。
结构的实际定义可能随具体实现有所不同,但其基本形式是:

struct stat{
    mode_t              st_mode;  /* file type & mode (permissions) */
    ino_t               st_ino;   /* i-node number (serial number) */
    dev_t               st_dev;   /* device number (file system) */
    nlink_t             st_rdev;  /* device number for special files */
    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 */
    struct timespec     st_atime; /* time of last access */
    struct timespec     st_mtime; /* time of last modification */
    struct timespec     st_ctime; /* time of last file status change */
    blksize_t           st_blksize;/* best I/O block size */
    blkcnt_t            st_blocks; /* number of disk blocks allocated */
};

POSIX.1 未要st_rdev, st_blksize和st_blocks字段。Single UNIX Specification XSI
扩展定义了这些字段。

timespec字段结构类型按照秒和纳秒定义了时间,至少包括下面两个字段:
time_t tv_sec;
long tv_nsec;
在2008年版本以前的标准中, 时间字段定义成st_atime、st_mtime以及st_ctime,它们都是time_t类型的(以秒来表示)。timespec结构提供了更高精准的时间戳。为了保持兼容性,旧的命字可以定义tv_sec成员。例如st_atime可以定义成st_atim.tv_sec。
注意:stat结构中的大多数成员都是基本系统数据类型如下图:
这里写图片描述
(基本系统数据类型定义之后,就不需要考虑因系统不同而变化的程序实现细节。即这些定义是为了实现程序的跨系统运行。)

使用stat函数最多的地方可能就是ls -l命令,用其可以获得有关一个文件的所有信息。

声明:该文观点仅代表作者本人,入门客AI创业平台信息发布平台仅提供信息存储空间服务,如有疑问请联系rumenke@qq.com。