stat函数学习
stat函数组
前面介绍的通过ls命令查看到的文件信息,都可以使用stat函数组提
取出来
• stat函数组
– 使用命令man stat查看相关文档
• 函数int stat(const char *path, struct stat *buf);
– 参数*path:文件路径
– 参数*buf:文件信息
– 返回值:成功为0,否则为-1
• 函数int fstat(int fd, struct stat *buf);
– 参数fd:文件描述符
– 参数*buf:文件信息
– 返回值:成功为0,否则为-1
• 函数int lstat(const char *path, struct stat *buf);
– 参数*path:文件路径
– 参数*buf:返回文件的信息,针对符号链接,lstat 返回链接本身,而不是
而非目标文件
– 返回值:成功为0,否则为-1
stat结构体:
struct stat {
dev_t st_dev; //文件的设备编号
ino_t st_ino; //节点
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; //文件字节数(文件大小)
unsigned long st_blksize; //块大小(文件系统的I/O 缓冲区大小)
unsigned long st_blocks; //块数
time_t st_atime; //最后一次访问时间
time_t st_mtime; //最后一次修改时间
time_t st_ctime; //最后一次改变时间(指属性)
};
小的测试程序:
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> int main(int argc,char *argv[]) { struct stat groupstat; int fd, ret; if(argc < 2) { printf("Please input file path\n"); return 0; } //stat test ret = stat(argv[1], &groupstat); if(ret) { printf("Please make sure file path\n"); return 0; } printf("%s inode number:%ld\n", argv[1], groupstat.st_ino); //fstat test fd = open(argv[1], O_RDWR|O_NOCTTY|O_NDELAY); if(fd < 0) { printf("open failed\n"); return 0; } ret = fstat(fd, &groupstat); if(ret) { printf("Please make sure file path\n"); return 0; } printf("fstat inode number:%ld\n", groupstat.st_ino); ret = lstat(argv[1], &groupstat); if(ret) { printf("Please make sure file path\n"); return 0; } printf("lstat inode number:%ld\n", groupstat.st_ino); return 0; }
无欲速,无见小利。欲速,则不达;见小利,则大事不成。