当前位置:   article > 正文

Linux下的stat()函数_linux stat函数

linux stat函数

Linux下的stat()函数

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

一、stat()函数

函数功能

通过文件名filename获取文件信息,并保存在buf所指的结构体stat中

#include <sys/stat.h>
#include <unistd.h>
int stat(const char *file_name, struct stat *buf);
  • 1
  • 2
  • 3

返回值:

执行成功则返回0,失败返回-1,错误代码存于errno

错误代码errno:

ENOENT 参数file_name指定的文件不存在
ENOTDIR 路径中的目录存在但却非真正的目录
ELOOP 欲打开的文件有过多符号连接问题,上限为16符号连接
EFAULT 参数buf为无效指针,指向无法存在的内存空间
EACCESS 存取文件时被拒绝
ENOMEM 核心内存不足
ENAMETOOLONG 参数file_name的路径名称太长

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 file system 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 */ 最后一次改变该文件状态的时间   
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

具体使用(代码演示)

使用stat函数打印出文件容量
代码如下(示例):

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <sys/stat.h>
  4 #include <unistd.h>
  5 
  6 
  7 int main(int vagr,const char **argv)
  8 {
  9   int ch;
 10   if(vagr <2)
 11   {
 12     fprintf(stderr,"输入参数过少\n");                                                                                               
 13   }
 14   struct stat buff;
 15  if(stat(argv[1],&buff)<0)//函数执行失败
 16  {
 17    fprintf(stderr,"执行失败\n");
 18    exit(1);
 19  }
 20   ch=buff.st_size;
 21   printf("文件大小为%d\n",ch);
 22 
 23 
 24   exit(0);
 25 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

运行结果为
****
结构显示正常,成功通过stat函数输出了文件字节大小

总结

在这里插入图片描述

判断文件类型宏

判断文件类型的函数,返回true,false  
 S_ISREG(stat.st_mode) is it a regular file?
 S_ISDIR(stat.st_mode) directory?
 S_ISCHR(stat.st_mode) character device?
 S_ISBLK(stat.st_mode) block device?
 S_ISFIFO(m) FIFO (named pipe)?
 S_ISLNK(stat.st_mode) symbolic link? (Not in POSIX.1-1996.)
 S_ISSOCK(stat.st_mode) socket? (Not in POSIX.1-1996.)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/523122
推荐阅读
相关标签
  

闽ICP备14008679号