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