stat函数和lstat函数

本文详细解析了stat和lstat两个系统调用的区别,特别是在处理链接文件时的行为差异。通过实例代码展示了如何使用这两个函数获取文件信息,并解释了struct stat结构体中关键字段的含义。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/欢迎大家批评指正/

stat和lstat是兄弟函数,都是用于获取文件信息
如果文件不是链接文件,则二者没有区别,如果是链接文件有如下区别:
stat:获取链接文件的信息时,具有穿透能力,直接穿越链接文件,获取所被链接文件的信息。
lstat:获取链接文件的信息,无穿透能力

函数原型
int stat(const char *pathname,struct stat *buf);
int lstat(const char *pathname,struct stat buf);
参数一:文件路径
参数二:用于存放文件信息的结构体(struct 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 512B blocks allocated */

mode_t st_mode; /* protection */ 文件属性
S_IFMT 0170000 文件类型位字段的位掩码
S_IFSOCK 0140000 套接字
S_IFLNK 0120000 符号链接
S_IFREG 0100000 普通文件
S_IFBLK 0060000 块设备
S_IFDIR 0040000 目录
S_IFCHR 0020000 字符设备
S_IFIFO 0010000 管道文件

用stat或lstat获取文件信息

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

#include <stdio.h>

int main(int argc,const char*argv[])   //执行  ./main filepath
{
	//获取文件的信息
	  //int stat(const char *path, struct stat *buf);
	  //struct stat *buf;
	  struct stat st;//存放文件信息的结构体
	  
	  int ret = stat(argv[1],&st);
	  // int ret = lstat(argv[1],&st);
	  if(ret == 0)
	  {
		  printf("获取信息成功\n");
	  }
	  printf("文件的大小为:%d\n",(int)st.st_size);
	  
	  if((st.st_mode & S_IFMT) == S_IFDIR)//S_IFMT 可判断其他类型 else if 并列判断
	  {
		  printf("该文件为普通类型的文件\n");
	  }
		return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值