2025年3月22日 星期六 甲辰(龙)年 月廿一 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > C语言

C语言 fstat函数

时间:03-14来源:作者:点击数:37

前言

一、stat系统调用

stat系统调用系列包括了fstat、stat和lstat,它们都是用来返回“相关文件状态信息”的,三者的不同之处在于设定源文件的方式不同。

二、fstat

1.功能

由文件描述符取得文件的状态。

2.相关函数

stat、lstat、chmod、chown、readlink、utime。

3.头文件

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

4.函数声明

  • int fstat (int filedes, struct *buf);

5.描述

fstat() 用来将参数filedes 所指向的文件状态复制到参数buf 所指向的结构中(struct stat), fstat() 与stat() 作用完全相同,不同之处在于传入的参数为已打开的文件描述符。

6.返回值

执行成功返回0,失败返回-1,错误代码保存在errno中。

7.例子

  • #include <stdio.h>
  • #include <stdlib.h>
  • #include <sys/stat.h>
  • #include <unistd.h>
  • #include <fcntl.h>
  • main()
  • {
  • struct stat buf;
  • int fd;
  • fd = open ("/etc/passwd", O_RDONLY);
  • fstat (fd, &buf);
  • printf("/etc/passwd file size = %d\n",(int)(buf.st_size));
  • }

执行结果:

/etc/passwd file size = 1656

三、struct stat结构体

  • struct stat{
  • __dev_t st_dev; /* Device. */
  • __field64(__ino_t, __ino64_t, st_ino); /* File serial number. */
  • __mode_t st_mode; /* File mode. */
  • __nlink_t st_nlink; /* Link count. */
  • __uid_t st_uid; /* User ID of the file's owner. */
  • __gid_t st_gid; /* Group ID of the file's group.*/
  • __dev_t st_rdev; /* Device number, if device. */
  • __dev_t __pad1;
  • __field64(__off_t, __off64_t, st_size); /* Size of file, in bytes. */
  • __blksize_t st_blksize; /* Optimal block size for I/O. */
  • int __pad2;
  • __field64(__blkcnt_t, __blkcnt64_t, st_blocks); /* 512-byte blocks */
  • #ifdef __USE_XOPEN2K8
  • /* Nanosecond resolution timestamps are stored in a format
  • equivalent to 'struct timespec'. This is the type used
  • whenever possible but the Unix namespace rules do not allow the
  • identifier 'timespec' to appear in the <sys/stat.h> header.
  • Therefore we have to handle the use of this header in strictly
  • standard-compliant sources special. */
  • struct timespec st_atim; /* Time of last access. */
  • struct timespec st_mtim; /* Time of last modification. */
  • struct timespec st_ctim; /* Time of last status change. */
  • # define st_atime st_atim.tv_sec /* Backward compatibility. */
  • # define st_mtime st_mtim.tv_sec
  • # define st_ctime st_ctim.tv_sec
  • #else
  • __time_t st_atime; /* Time of last access. */
  • unsigned long int st_atimensec; /* Nscecs of last access. */
  • __time_t st_mtime; /* Time of last modification. */
  • unsigned long int st_mtimensec; /* Nsecs of last modification. */
  • __time_t st_ctime; /* Time of last status change. */
  • unsigned long int st_ctimensec; /* Nsecs of last status change. */
  • #endif
  • int __glibc_reserved[2];
  • };
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门