3.2.3.1、用代码判断文件类型
(1)文件类型就是-、d、l····
(2)文件属性中的文件类型标志在struct stat结构体的mode_t st_mode元素中,这个元素其实是一个按位来定义的一个位标志(有点类似于ARM CPU的CPSR寄存器的模式位定义)。这个东西有很多个标志位共同构成,记录了很多信息,如果要查找时按位&操作就知道结果了,但是因为这些位定义不容易记住,因此linux系统给大家事先定义好了很多宏来进行相应操作。
(3)譬如S_ISREG宏返回值是1表示这个文件是一个普通文件,如果文件不是普通文件则返回值是0.
实例 S_ISREG 用来查询是不是普通文件
int result = S_ISREG(buf.st_mode);
#include "stdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#define NAME "1.txt"
int main(void)
{
int ret = -1;
struct stat buf ;
memset(&buf, 0, sizeof(buf));//清空结构体 buf , buf 全是 0
ret = stat(NAME,&buf); // stat 后 buf 就有内容了
if(ret<0)
{
perror("stat");
exit(-1);
}
//判断文件的属性
int result = S_ISREG(buf.st_mode);
printf("result = %d. \n",result);
return 0;
}
运行结果 : 返回 1 ,表示普通文件
实例 查询是 不是文件夹 S_ISDIR(m)
#include "stdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#define NAME "1.txt"
int main(void)
{
int ret = -1;
struct stat buf ;
memset(&buf, 0, sizeof(buf));//清空结构体 buf , buf 全是 0
ret = stat(NAME,&buf); // stat 后 buf 就有内容了
if(ret<0)
{
perror("stat");
exit(-1);
}
//判断文件的属性
int result = S_ISDIR(buf.st_mode); //查询文件夹 S_ISDIR
printf("result = %d. \n",result);
return 0;
}
运行结果:
各种属性
3.2.3.2、用代码判断文件权限设置
(1)st_mode中除了记录了文件类型之外,还记录了一个重要信息:文件权限。
(2)linux并没有给文件权限测试提供宏操作,而只是提供了位掩码,所以我们只能用位掩码来自己判断是否具有相应权限。
实例: 文件权限测试
S_IRUSR 返回0 :代表不具有 读取 的权限
返回1 :代表具有 读取 的权限
#include "stdio.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#define NAME "1.txt"
int main(void)
{
int ret = -1;
struct stat buf ;
memset(&buf, 0, sizeof(buf));//清空结构体 buf , buf 全是 0
ret = stat(NAME,&buf); // stat 后 buf 就有内容了
if(ret<0)
{
perror("stat");
exit(-1);
}
//文件权限测试 S_IRUSR 返回0 :代表不具有 读取 的权限
int result =((buf.st_mode & S_IRUSR) ? 1:0); //宿主读取权限 (buf.st_mode & S_IRUSR)这个结果只要不等于0, 就是1 !!!
printf("file owner = %d. \n",result);
return 0;
}
运行结果:
更改文件权限:
chmod u-r 1.txt 就是把 1.txt 可读权限去掉
chmod u+r 1.txt 就是把 1.txt 可读权限加上
代码来自: 朱老师物联网大讲堂