通过系统函数lstat或者stat,获取文件类型和文件权限用法

stat函数和lstat可以获取文件权限和文件类型。注意lstat没有对软连接的穿透,所以可以获取软连接文件类型,stat则不可以。这是官方的给的文档

int stat(const char *pathname, struct stat *statbuf);
int lstat(const char *pathname, struct stat *statbuf);

           struct stat {
               dev_t     st_dev;         /* ID of device containing file */
               ino_t     st_ino;         /* Inode number */
               mode_t    st_mode;        /* File type and mode 文件类型和问价属性*/
               nlink_t   st_nlink;       /* Number of hard links */
               uid_t     st_uid;         /* User ID of owner */
               gid_t     st_gid;         /* Group ID of owner */
               dev_t     st_rdev;        /* Device ID (if special file) */
               off_t     st_size;        /* Total size, in bytes */
               blksize_t st_blksize;     /* Block size for filesystem I/O */
               blkcnt_t  st_blocks;      /* Number of 512B blocks allocated */

               /* 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;  /* Time of last access */
               struct timespec st_mtim;  /* Time of last modification */
               struct timespec st_ctim;  /* Time of last status change */

           #define st_atime st_atim.tv_sec      /* Backward compatibility */
           #define st_mtime st_mtim.tv_sec
           #define st_ctime st_ctim.tv_sec
           };

例子如下,使用时可以直接复制,经测试可以运行

int main(int argc,char *argv[])
{
	struct stat st;
	lstat(argv[1],&st);
	//打印文件的大小,uid和gid
	printf("size[%d]  uid:[%d]   gid:[%d]\n",st.st_size,st.st_uid,st.st_gid);

	//定义数组,用来存储文件的类型及权限
	char *str[10];
	//初始化数组
	for(int i=0;i<=9;i++)
	{
		str[i]="-";
	}
	int mode=st.st_mode;

	//判断文件属性,存到str[0]
	if(S_ISREG(mode)) str[0] = "普通文件";
	else if(S_ISDIR(mode)) str[0] = "目录";
	else if(S_ISBLK(mode)) str[0] = "块设备";
	else if(S_ISCHR(mode)) str[0] = "字符设备";
	else if(S_ISFIFO(mode)) str[0] = "管道";
	else if(S_ISLNK(mode)) str[0] = "软连接";
	else if(S_ISSOCK(mode)) str[0] = "套接字";
	//打印文件类型
	printf("%s   ",str[0]);
	
	//判断文件权限,存到数组中
	if ( mode & S_IRUSR ) str[1] = "r";    /* 3 bits for user  */
	if ( mode & S_IWUSR ) str[2] = "w";
	if ( mode & S_IXUSR ) str[3] = "x";

	if ( mode & S_IRGRP ) str[4] = "r";    /* 3 bits for group */
	if ( mode & S_IWGRP ) str[5] = "w";
	if ( mode & S_IXGRP ) str[6] = "x";

	if ( mode & S_IROTH ) str[7] = "r";    /* 3 bits for other */
	if ( mode & S_IWOTH ) str[8] = "w";
	if ( mode & S_IXOTH ) str[9] = "x";
	//打印文件权限
	for(int i=1;i<=9;i++)
	{
		printf("%s",str[i]);
	}
	putchar('\n');
	return 0;


}

测试结果如下:
在这里插入图片描述在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值