stat/fstat/l_stat
#include <sys/stat.h>
功能:用来获取文件属性,返回值:成功返回0,失败返回-1
int stat(const char *path, struct stat *buf);
path:需要文件路径
int fstat(int fd, struct *buf);
fd:需要打开后的文件描述符
int lstat(const char *path, struct stat *buf);
stat/fstat会跟踪链接目标,而lstat不跟踪链接目标。
struct stat {
dev_t st_dev; // 设备id
ino_t st_ino; // 节点号
mode_t st_mode; // 文件类型和权限
nlink_t st_nlink; // 硬链接数
uid_t st_uid; // 用户ID
gid_t st_gid; // 组ID
dev_t st_rdev; // 特殊设备ID
off_t st_size; // 文件的总字节数
blksize_t st_blksize; // IO块数
blkcnt_t st_blocks; // 占用块(512字节)
time_t st_atime; // 最后访问时间
time_t st_mtime; // 最后修改时间
time_t st_ctime; // 最后的文件属性修改时间
};
以下POSIX宏被定义为使用st_mode字段:
S_ISREG(m) 测试是否是标准文件 is it a regular file?
S_ISDIR(m) 目录 directory?
S_ISCHR(m) 字符设备文件 character device?
S_ISBLK(m) 块设备文件 block device?
S_ISFIFO(m) 管道文件 FIFO (named pipe)?
S_ISLNK(m) 链接文件 symbolic link? (Not in POSIX.1-1996.)
S_ISSOCK(m) socket文件 socket?
为st_mode字段定义了以下标志:
S_IFMT 0170000 获取文件类型出错 bit mask for the file type bit fields
S_IFSOCK 0140000 socket文件
S_IFLNK 0120000 软链接 symbolic link
S_IFREG 0100000 标准文件 regular file
S_IFBLK 0060000 块设备 block device
S_IFDIR 0040000 目录 directory
S_IFCHR 0020000 字符设备 character device
S_IFIFO 0010000 管道文件 FIFO
S_ISUID 0004000 设置uid位 set UID bit
S_ISGID 0002000 设置组ID位 set-group-ID bit (see below)
S_ISVTX 0001000 粘滞位 sticky bit (see below)
S_IRWXU 00700 获取权限 mask for file owner permissions
S_IRUSR 00400 所有者具有读取权限 owner has read permission
S_IWUSR 00200 所有者具有写入权限 owner has write permission
S_IXUSR 00100 属主的执行权限 owner has execute permission
S_IRWXG 00070 所有者具有执行权限 mask for group permissions
S_IRGRP 00040 组具有读取权限 group has read permission
S_IWGRP 00020 组具有写入权限 group has write permission
S_IXGRP 00010 组具有执行权限 group has execute permission
S_IRWXO 00007 其他人权限的掩码(不在组中) mask for permissions for others (not in group)
S_IROTH 00004 其他人有读权限 others have read permission
S_IWOTH 00002 其他人有写权限 others have write permission
S_IXOTH 00001 其他人有执行权限 others have execute permission
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main()
{
int fd = open("1.txt", O_RDONLY);
struct stat buf;
fstat(fd, &buf);
printf("st_dev:%u\n",(unsigned int)buf.st_dev);
printf("st_ino:%lu\n",buf.st_ino);
printf("st_mode:%u\n",buf.st_mode);
printf("st_nlink:%u\n",buf.st_nlink);
printf("st_uid:%u\n",buf.st_uid);
printf("st_gid:%u\n",buf.st_gid);
printf("st_rdev:%u\n",(unsigned int)buf.st_rdev);
printf("st_size:%lu\n",buf.st_size);
printf("st_blksize:%lu\n",buf.st_blksize);
printf("st_blocks:%u\n",(unsigned int)buf.st_blocks);
printf("st_atime:%lu\n",buf.st_atime); // 可以使用localtime转换输出
printf("st_mtime:%lu\n",buf.st_mtime);
printf("st_ctime:%lu\n",buf.st_ctime);
}
参考源自:Linux丰富的帮助手册。终端执行man 2 stat,即可找到相关资料
相关应用参考:高仿linux下的ls -l命令——C语言实现