fstat函数
功能
由文件描述符获取文件的状态
头文件
#include <sys/stat.h>
#include <unistd.h>
函数声明
int fstat(int filedes, struct *buf);
两个参数分别为:
int filedes: 已经打开的文件描述符,通常由 open
函数返回
struct *buf: 用来存放fstat所获取的文件的状态。
fstat() 用来将参数filedes 所指向的文件状态复制到参数buf 所指向的结构中(struct stat), fstat() 与stat() 作用完全相同,不同之处在于传入的参数为已打开的文件描述符。
返回值
执行成功返回0,否则返回-1
例子
#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];
};