获取文件信息

struct stat

fd_(::open(filename.c_str(), O_RDONLY | O_CLOEXEC))
fd_ 用于打开一个文件,作为 file descriptor

      struct stat statbuf;
      // 获取 文件的信息 存放在 statbuf 中
      if (::fstat(fd_, &statbuf) == 0)
      {
        // 判断是否是一个常规文件
        if (S_ISREG(statbuf.st_mode))
        {
          // 获得文件的大小
          *fileSize = statbuf.st_size;
          // std::string::reserve()
          content->reserve(static_cast<int>(std::min(implicit_cast<int64_t>(maxSize), *fileSize)));
        }
        else if (S_ISDIR(statbuf.st_mode))
        {
          err = EISDIR;
        }
        if (modifyTime)
        {
          *modifyTime = statbuf.st_mtime;   // 获得文件的更新时间
        }
        if (createTime)
        {
          *createTime = statbuf.st_ctime;   // 获得文件的创建时间
        }
      }

::fstat

使用该函数需要
#include <sys/stat.h>
函数原型为

int fstat64 (int __fd, struct stat64 *__buf);

fd_ 是已经打开的文件的 file descriptor , 该函数获取该文件的信息并保存到结构体 buf 中,该结构体就是上述的 struct stat.
struct stat 结构体详细如下

struct stat64
  {
    __dev_t st_dev;		/* Device.  */

    __ino64_t st_ino;		/* File serial number.  */
    __nlink_t st_nlink;		/* Link count.  */
    __mode_t st_mode;		/* File mode.  */

    __uid_t st_uid;		/* User ID of the file's owner.	*/
    __gid_t st_gid;		/* Group ID of the file's group.*/

    int __pad0;
    __dev_t st_rdev;		/* Device number, if device.  */
    __off_t st_size;		/* Size of file, in bytes.  */

    __blksize_t st_blksize;	/* Optimal block size for I/O.  */
    __blkcnt64_t st_blocks;	/* Nr. 512-byte blocks allocated.  */
# 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.  */
# else
    __time_t st_atime;			/* Time of last access.  */
    __syscall_ulong_t st_atimensec;	/* Nscecs of last access.  */
    __time_t st_mtime;			/* Time of last modification.  */
    __syscall_ulong_t st_mtimensec;	/* Nsecs of last modification.  */
    __time_t st_ctime;			/* Time of last status change.  */
    __syscall_ulong_t st_ctimensec;	/* Nsecs of last status change.  */
# endif
    __syscall_slong_t __glibc_reserved[3];
  };
#endif

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值