stat函数和lstat函数

/欢迎大家批评指正/

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;
}

猜你喜欢

转载自blog.csdn.net/weixin_43657281/article/details/83956953