C++(www.cppentry.com)如何获取文件属性,stat系统调用系列包括了fstat、stat和lstat,它们都是用来返回“相关文件状态信息”的,三者的不同之处在于设定源文件的方式不同。
stat系统调用系列包括了fstat、stat和lstat,它们都是用来返回“相关文件状态信息”的,三者的不同之处在于设定源文件的方式不同。
1
首先隆重介绍的是一个非常重要的”VIP”人物,他是fstat, stat和lstat三者都要用到的一个结构体类型,名字叫做struct stat。可以说,没有这个struct stat的支持,上述三个系统调用将寸步难行。
这个struct stat结构体在不同的Unix/Linux系统中的定义是有小的区别的,但你完全不用担心,这并不会影响我们的使用。
在struct stat结构体中我们常用的且各个平台都一定有的域是:
st_mode 文件权限和文件类型信息 (记住这个黑体橘红色)
st_ino 与该文件关联的inode
st_dev 保存文件的设备
st_uid 文件属主的UID号
st_gid 文件属主的GID号
st_atime 文件上一次被访问的时间
st_ctime 文件的权限、属主、组或内容上一次被修改的时间
st_mtime 文件的内容上一次被修改的时间。(和st_ctime的不同之处显而易见)
st_nlink 该文件上硬连接的个数
我分别提取了solaris(UNIX)和fedora(Linux)的struct stat结构体的原始定义:大家可以自己比对一下便可以发现两者确实有所不同,但主要的域是完全相同的。
solaris的struct stat定义:
struct stat {
dev_t st_dev;
ino_t st_ino;
mode_t st_mode;
nlink_t st_nlink;
uid_t st_uid;
gid_t st_gid;
dev_t st_rdev;
off_t st_size;
timestruc_t st_atim;
timestruc_t st_mtim;
timestruc_t st_ctim;
blksize_t st_blksize;
blkcnt_t st_blocks;
char st_fstype[_ST_FSTYPSZ];
};
fedora的struct stat定义:
struct stat
{
__dev_t st_dev; /* Device. */
unsigned short int __pad1;
__ino_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. */
unsigned short int __pad2;
__off_t st_size; /* Size of file, in bytes. */
__blksize_t st_blksize; /* Optimal block size for I/O. */
__blkcnt_t st_blocks; /* Number 512-byte blocks allocated. */
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. */
unsigned long int __unused4;
unsigned long int __unused5;
};