获取文件属性
Int stat(const char *filename, structstat*buf)
Int fstat(int filedes, struct stat *buf)
Int lstat(const char *filename, struct stat*buf)
返回值
成功:0
错误:-1
Stat:用于获取由参数file_name指定的文件名的状态信息,保存在参数struct stat *buf中。
Fstat与stat的区别在于fstat是通过文件描述符来指定文件的。
Lstat与stat的区别在于,对于符号连接文件,lstat返回的是符号连接文件本身的状态信息,而stat返回的是符号链接指向的文件状态信息
Struct stat{
Dev_t st_dev;//文件的设备编号
Ino_t st_ino; //文件的i-node(i节点编号)
Mode_t st_mode;//文件的类型和存取权限
Nlink_t st_nlink;//连接到该文件的硬链接数目,刚建立的文件值为1
Uid_t st_uid;//用户id
Gid_t st_gid;//组id
Dev_t st_rdev;//若文件为设备文件,则为其设备编号
Off_t st_size;//文件大小,以字节计算,对于符号链接,该大小是其所指向的文件名的长度
Blksize_t st_blksize;//文件系统的i/o缓冲区大小
Blkont_t st_blocks;//占用文件区块的个数,每一区块大小通常为512字节
Time_t st_atime;//文件最近一次被访问时间
Time_t st_mtime;//文件最后一次被修改的时间,一般只能调用utime和write函数时才会改变
Time_t st_otime;//文件最近一次被更改的时间,此参数在文件所有者,所属组,文件权限被更改是更新
}
对于st_mode包含的文件类型信息,POSIX标准定义了一系列的宏
S_ISLNK:判断是否为符号链接
S_ISREG:判断是否为一般文件
S_ISDIR:判断是否为目录文件
S_ISCHR:判断是否为字符设备文件
S_ISBLK:判断是否为块设备文件
S_ISFIFO:判断是否为FIFO
S_ISSOCK:判断是否为SOCKET
常用的有:st_mode,st_uid,st_gid,st_size,st_atime,st_mtime
代码:
#include <stdio.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
int main(int argc, char **argv)
{
structstat buf;
if(argc != 2)
{
printf("Usage:./stat <filename>\n");
exit(0);
}
if(stat(argv[1], &buf) == -1)
{
printf("stat:error!\n");
exit(1);
}
printf("deviceis: %d\n", buf.st_dev);
printf("inodeis: %d\n", buf.st_ino);
printf("modeis: %o\n", buf.st_mode);
printf("totalsize, in bytes is: %d\n", buf.st_size);
printf("timeof last access is: %s\n", ctime(&buf.st_atime));
}