获取文件属性信息之stat、fstat和lstat

it2022-05-05  38

UNIX文件系统是目录和文件组成的一种层次结构。目录(directory)是一个包含许多目录项的文件,在逻辑上,可以认为每个目录项都包含一个文件名,同时还包含说明该文件属性的信息。文件属性是指文件类型(是普通文件还是目录)、文件大小、文件所有者、文件权限以及文件最后的修改时间等。stat和fstat函数可获取包含文件所有属性的一个信息结构(可使用man fstat查看这两个函数的帮助信息)。

stat, fstat, lstat – 获取文件属性信息

SYNOPSIS        #include <sys/types.h>        #include <sys/stat.h>        #include <unistd.h>

int stat(const char *path, struct stat *buf);        int fstat(int filedes, struct stat *buf);        int lstat(const char *path, struct stat *buf);

DESCRIPTION

这些函数获取文件属性信息。对文件本身不需要任何权限,但是stat和lstat,需要对到达该文件的路径上的所有目录具有可执行权限才可获取该文件属性信息。

stat函数统计由path指向的文件的属性信息并将该属性信息结构存入buf中;

lstat函数与stat函数功能完全一样,不同的是,如果它的文件路径path是一个软连接,那么统计的是该软连接的信息,而不是该链接指向的文件的属性信息。

fstat函数与stat函数功能也完全一样,不同的是,该函数所统计的文件是由文件描述符filedes指定的。

上述三个函数成功返回0,失败返回-1.

通过上面这三个函数都可以获取到文件的一个stat结构体,该结构体定义如下:

struct stat {              dev_t     st_dev;     /* ID of device containing file */              ino_t     st_ino;     /* inode number */              mode_t    st_mode;    /* protection */              nlink_t   st_nlink;   /* number of hard links */              uid_t     st_uid;     /* user ID of owner */              gid_t     st_gid;     /* group ID of owner */              dev_t     st_rdev;    /* device ID (if special file) */              off_t     st_size;    /* total size, in bytes */              blksize_t st_blksize; /* blocksize for filesystem I/O */              blkcnt_t  st_blocks;  /* number of blocks allocated */              time_t    st_atime;   /* time of last access */              time_t    st_mtime;   /* time of last modification */              time_t    st_ctime;   /* time of last status change */          };

简单尝试着用一下stat函数获取文件属性信息:

[root@localhost test]# cat test.c #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> int main(void) { struct stat buffer; stat("/home/zhu/test", &buffer); printf( "st_uid :%d\n", buffer.st_uid); printf( "st_gid :%d\n", buffer.st_gid); printf( "st_blocks :%d\n", buffer.st_blocks); printf( "st_atime :%d\n", buffer.st_atime); printf( "st_mtime :%d\n", buffer.st_mtime); printf( "st_ctime :%d\n", buffer.st_ctime); return 0; }

运行结果:

[root@localhost test]# ./test st_uid :0 st_gid :0 st_blocks :16 st_atime :1388148620 st_mtime :1388151845 st_ctime :1388151845

转载于:https://www.cnblogs.com/nufangrensheng/p/3494809.html


最新回复(0)