stat()函数 获取文件类型

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;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值