fstat().stat()函数

时间:2023-03-09 15:15:34
fstat().stat()函数

int stat(const char *path, struct stat *buf);

int fstat(int fd, struct stat *buf);

唯一不同是参数不同,其他一样。

文件的一些属性参数:

struct stat{

  dev_t st_dev; /* ID of device containing file */
  ino_t st_ino; /* inode number */ 文件inode号
  mode_t st_mode; /* protection */ 
  nlink_t st_nlink; /* number of hard links */ 硬链接数
  uid_t st_uid; /* user ID of owner */  文件的UID
  gid_t st_gid; /* group ID of owner */文件的GID
  dev_t st_rdev; /* device ID (if special file) */设备ID(如果特殊的文件)
  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 */ 文件的三个时间atime mtime atime
  time_t st_mtime; /* time of last modification */
  time_t st_ctime; /* time of last status change */
};

 通过下面的一些宏函数定义可以判断文件类型:

The following POSIX macros are defined to check the file type using the st_mode field:

下面的POSIX宏定义使用st_mode字段检查文件类型:

如果如下宏返回真就说明是所指文件

if( S_ISREG(st_mode) )

{

说明是普通文件

}

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.)套接字

例子:

int main(int argc , char* argv[])
{
  struct stat fileinfo;
  int fd;
  if(argc > 2 ) return 0;

  fd = open(argv[1] , O_RDONLY);

  if(fd == -1)
  {
    printf("%s\n" , strerror(errno));
  }
  else
  {
    fstat(fd , &fileinfo);//获取文件属性 //stat只需要改下参数即可

    if( S_ISREG(fileinfo.st_mode) )
    {
      printf("普通文件\n");
    }
  }
  close(fd);

  return 0;

}