stat()/lstat()函数使用

stat()/lstat()函数

功能

获取文件属性

定义函数

函数原型:
int stat(const char *pathname, struct stat *buf);
int lstat(const char *pathname, struct stat *buf);
函数返回值:
成功为:0
失败为:-1

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;      //文件字节数(文件大小)
	    blksize_t       st_blksize;   //块大小(文件系统的I/O 缓冲区大小)
	    blkcnt_t        st_blocks;    //块数
	    time_t         st_atime;     //最后一次访问时间
	    time_t         st_mtime;     //最后一次修改时间
	    time_t         st_ctime;     //最后一次改变时间(指属性)
	};

样例

//stat函数测试: 获取文件大小, 文件属主和组
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc, char *argv[])
{
	//int stat(const char *pathname, struct stat *buf);
	struct stat st;
	stat(argv[1], &st);
	printf("size:[%d], uid:[%d], gid:[%d]\n", st.st_size, st.st_uid, st.st_gid);

	return 0;
}

stat()/lstat()函数使用

st_mode

mode_t st_mode; //文件的类型和存取的权限[注]:mode_t st_mode 是 struct stat 中成员

0-2 bit -- 其他*限
			S_IROTH    00004  读权限
			S_IWOTH    00002  写权限
			S_IXOTH    00001  执行权限
			S_IRWXO    00007  掩码, 过滤 st_mode中除其他*限以外的信息
3-5 bit -- 所属组权限
			S_IRGRP    00040  读权限
			S_IWGRP    00020  写权限
		    S_IXGRP    00010  执行权限
			S_IRWXG    00070  掩码, 过滤 st_mode中除所属组权限以外的信息
6-8 bit -- 文件所有者权限
			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-15 bit -- 文件类型
			S_IFSOCK          0140000 套接字
			S_IFLNK           0120000 符号链接(软链接)
		    S_IFREG           0100000 普通文件
			S_IFBLK           0060000 块设备
			S_IFDIR           0040000 目录
		    S_IFCHR           0020000 字符设备
			S_IFIFO           0010000 管道
			S_IFMT            0170000 掩码,过滤 st_mode中除文件类型以外的信息
			if ((st_mode & S_IFMT)==S_IFREG) ----为真普通文件
            if(S_ISREG(st_mode))     ------为真表示普通文件
            if(S_ISDIR(st.st_mode))  ------为真表示目录文件

stat函数和lstat函数的区别:

  1. 对于普通文件, 这两个函数没有区别, 是一样的.
  2. 对于连接文件,调用lstat函数获取的是链接文件本身的属性信息;而stat函数获取的是链接文件指向的文件的属性信息.
上一篇:第 19 次 CCF CSP 认证(前三题)


下一篇:kuangbin带你飞 专题十五 数位DP