stat系统调用系列包括了fstat、stat和lstat,它们都是用来返回“相关文件状态信息”的,三者的不同之处在于设定源文件的方式不同。
由文件描述符取得文件的状态。
stat、lstat、chmod、chown、readlink、utime。
- #include <sys/stat.h>
- #include <unistd.h>
-
- int fstat (int filedes, struct *buf);
-
fstat() 用来将参数filedes 所指向的文件状态复制到参数buf 所指向的结构中(struct stat), fstat() 与stat() 作用完全相同,不同之处在于传入的参数为已打开的文件描述符。
执行成功返回0,失败返回-1,错误代码保存在errno中。
- #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{
- __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];
- };
-