前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >stat函数的用法_Str函数

stat函数的用法_Str函数

作者头像
全栈程序员站长
发布2022-09-24 13:35:55
5100
发布2022-09-24 13:35:55
举报

大家好,又见面了,我是你们的朋友全栈君。

/欢迎大家批评指正/

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获取文件信息

代码语言:javascript
复制
#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;
}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/171807.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档