1.函数原型
int stat(const char *path, struct stat *buf);
2.函数结构体
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 512B 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 函数
获取文件属性(从inode结构体获取)
int stat(const char *path, struct stat *buf);成功返回0 失败-1
参数1:文件名
参数2: inode结构体指针(传出参数)
3.通过宏函数
st_mode field: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? (Not in POSIX.1-1996.)
命令创建 FIFO 文件 mkfifo 文件名
stat函数默认是可以 穿透软、硬链接文件 直接 获取 链接指向的 文件inode
想要检测文件是否是 link 类型, 则需要换函数 stat -> lstat
穿透符号链接:stat:会 lstat:不会
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <string.h>
int main(int argc, char *argv[])
{
struct stat stat_buf;
int ret = stat(argv[1], stat_buf);
if(ret == -1)
{
perror("stat error\n");
exit(1);
}
if(S_ISREG(stat_buf.st_mode)) //判断是否普通文件
{
printf("Is's a regular\n");
}else if(S_ISDIR(sbuf.st_mode)){ //判读是否目录
printf("Is's a dir\n");
}else if(S_ISCHR(sbuf.st_mode)){ //判断是否字符设备
printf("Is's a char device\n");
}else if(S_ISFIFO(sbuf.st_mode)){ //判断是否管道
printf("Is's a fifo\n");
}
return 0;
}