糖尿病康复,内容丰富有趣,生活中的好帮手!
糖尿病康复 > 函数stat fstat fstatat和lstat

函数stat fstat fstatat和lstat

时间:2019-09-09 22:39:26

相关推荐

函数stat fstat fstatat和lstat

一、主要函数应用

#include <sys/stat.h>int stat(const char *path, struct stat *buf);int fstat(int fd, struct stat *buf)int lstat(const char *path, struct stat *buf);int fstat(int fd, const char *path, struct stat *buf, int flag);

参数:

stat读取的是连接文件指向的文件的属性lstat读取的链接文件本身的属性lstat

二、struct stat 的结构体

struct stat {dev_t st_dev; //文件的设备编号ino_t st_ino; //节点mode_t st_mode;//文件的类型和存取的权限nlink_tst_nlink;//连到该文件的硬连接数目,刚建立的文件值为1uid_t st_uid; //用户IDgid_t st_gid; //组IDdev_t st_rdev;//(设备类型)若此文件为设备文件,则为其设备编号off_t st_size;//文件字节数(文件大小)blksize_t st_blksize; //块大小(文件系统的I/O 缓冲区大小)blkcnt_t st_blocks; //块数time_t st_atime;//最后一次访问时间time_t st_mtime;//最后一次修改时间time_t st_ctime;//最后一次改变时间(指属性)};

三、st_mode 的结构

15-12 位保存文件类型11-9 位保存执行文件时设置的信息8-0 位保存文件访问权限

图1 展示了 st_mode 各个位的结构。

四、一些常用的宏

-st_mode -- 16位整数○ 0-2 bit -- 其他人权限- S_IROTH00004 读权限- S_IWOTH00002 写权限- S_IXOTH00001 执行权限- S_IRWXO00007 掩码, 过滤 st_mode中除其他人权限以外的信息○ 3-5 bit -- 所属组权限- S_IRGRP00040读权限- S_IWGRP00020写权限- S_IXGRP00010执行权限- S_IRWXG00070掩码, 过滤 st_mode中除所属组权限以外的信息○ 6-8 bit -- 文件所有者权限- S_IWUSR00200写权限- S_IXUSR00100执行权限- S_IRWXU00700掩码, 过滤 st_mode中除文件所有者权限以外的信息○ 12-15 bit -- 文件类型- S_IFSOCK0140000 套接字- S_IFLNK0120000 符号链接(软链接)- S_IFBLK0060000 块设备- S_IFDIR0040000 目录- S_IFCHR0020000 字符设备- S_IFIFO0010000 管道- S_IFMT 0170000 掩码,过滤 st_mode中除文件类型以外的信息(st_mode & S_IFMT) == S_IFREG

五、程序清单

测试代码:

#include <stdio.h> #include <sys/stat.h> #include <stdlib.h>int main(){struct stat st;struct stat* st1;st1 = &st;int ret = stat("english.txt", &st);if(ret == -1) {perror("stat error");exit(1);}printf("file size = %d\n", (int)st.st_size);return 0;}

输出结果:

#include <stdio.h> #include <sys/stat.h> #include <stdlib.h>int main(){struct stat st;struct stat* st1;st1 = &st;int ret = stat("english.txt", &st);if(ret == -1) {perror("stat error");exit(1);}printf("file size = %d\n", (int)st.st_size);if(st.st_mode & S_IFMT == S_IFREG) {printf("这是一个普通文件\n");}if(st.st_mode & S_IRUSR) {printf(" R ");}if(st.st_mode & S_IWUSR) {printf(" W ");}if(st.st_mode & S_IXUSR) {printf(" X ");}printf("\n");return 0;}

输出结果:

#include <stdio.h> #include <sys/stat.h> #include <stdlib.h>int main(){struct stat st;struct stat* st1;st1 = &st;int ret = lstat("s.s", &st);if(ret == -1) {perror("stat error");exit(1);}printf("file size = %d\n", (int)st.st_size);if(st.st_mode & S_IFMT == S_IFREG) {printf("这是一个普通文件\n");}if(st.st_mode & S_IRUSR) {printf(" R ");}if(st.st_mode & S_IWUSR) {printf(" W ");}if(st.st_mode & S_IXUSR) {printf(" X ");}printf("\n");return 0;}

输出结果:

参考资料:

1.12-stat 函数

2.13-stat 结构体 st_mode 字段

如果觉得《函数stat fstat fstatat和lstat》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。