大家好,欢迎来到IT知识分享网。
stat函数
函数描述:获取文件属性
函数原型:
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> int stat(const char *pathname, struct stat *buf);
函数返回值:
成功 :返回0
失败 :返回-1
参数类型:
pathname :为待解析文件的路径名,可以为绝对路径,也可以为相对路径
buf :为传出参数,传出文件的解析结果,buf为struct stat*类型,需要进一步解析,获取到的文件属性信息,就记录在struct stat结构体中
struct stat结构体:
在man配置中,struct stat结构体如下: struct stat { dev_t st_dev; /* 文件设备编号 */ ino_t st_ino; /* inode节点 */ 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缓冲区大小) */ blkcnt_t st_blocks; /* 块数 */ /* Since Linux 2.6, the kernel supports nanosecond precision for the following timestamp fields. For the details before Linux 2.6, see NOTES. */ struct timespec st_atim; /* 最后一次访问时间 */ struct timespec st_mtim; /* 最后一次修改时间(指文件内容) */ struct timespec st_ctim; /* 最后一次属性改变的时间 */ #define st_atime st_atim.tv_sec #define st_mtime st_mtim.tv_sec #define st_ctime st_ctim.tv_sec };
st_mode表示文件的类型和存取的权限,为16位整数
//0-2bit--其他人权限 S_IROTH 00004 读权限 S_IWOTH 00002 写权限 S_IXOTH 00001 执行权限 S_IRWXO 00007 掩码,过滤st_mode中除其他人权限以外的信息 //3-5bit--所属组权限 S_IRGRP 00040 读权限 S_IWGRP 00020 写权限 S_IXGRP 00010 执行权限 S_IRWXG 00070 掩码,过滤st_mode中除所属组权限以外的信息 //6-8bit--文件所有者权限 S_IRUSR 00400 读权限 S_IWUSR 00200 写权限 S_IXUSR 00100 执行权限 S_IRWXU 00700 掩码,过滤st_mode中除文件所有者权限以外的信息
- if(st_mode & S_IRUSR)//—–为真,表示可读
- if(st_mode & S_IWUSR)//—–为真,表示可写
- if(st_mode & S_IXUSR)//—–为真,表示可执行
//12-15bit--文件类型 S_IFSOCK 0 socket(套接字) S_IFLNK 0 symbolic link(软连接) S_IFREG 0 regular file(普通文件) S_IFBLK 0060000 block device(块设备文件) S_IFDIR 0040000 directory(目录) S_IFCHR 0020000 character device(字符设备文件) S_IFIFO 0010000 FIFO(管道) S_IFMT 0 掩码,过滤st_mode中除文件类型以外的信息
- if(( st_mode & S_IFMT) == S_IFREG)//—–为真,表示普通文件
- if(S_ISREG (st_mode)) //—–为真,表示普通文件
- if(S_ISDIR (st_mode)) //—–为真,表示目录文件
实例:
(1)stat获取文件的大小
#include<sys/stat.h> int main(int argc, char* argv[]) { struct stat statbuf; stat(argv[1], &statbuf); printf("%lu\n", statbuf.st_size); return 0; }
输出结果:查看text.x文件的大小
(2)stat获取文件类型
#include<sys/stat.h> int main(int argc, char* argv[]) { struct stat statbuf; stat(argv[1], &statbuf); printf("%lu\n",statbuf.st_size); //获取文件类型,S_IFREG表示普通文件 if((statbuf.st_mode & S_IFMT) == S_IFREG) { printf("这是一个普通文件\n"); } return 0; }
输出结果:
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://haidsoft.com/121730.html