hks_file_operator.c文件分析
该文件主要是鸿蒙当中文件的相关函数,主要涉及文件的读写删除,还有文件权限的赋值。以及文件路径读取,文件存在的判断等等相关功能。 文件路径:security_huks\services\huks_standard\huks_service\main\os_dependency\posix\hks_file_operator.c
一、代码分析获取文件名的函数(指的是全名) 参数魏路径,文件名和带路径的文件全名,以及全名的长度
//获取文件名,参数为路径,一个存放文件名的数组和一个全名数组以及全名长度
static int32_t GetFileName(const char *path, const char *fileName, char *fullFileName, uint32_t fullFileNameLen)
{
if (path != NULL) {
//检查路径是否为空,不为空将path写进fullFileName,长度strlen(path)
if (strncpy_s(fullFileName, fullFileNameLen, path, strlen(path)) != EOK) {
return HKS_ERROR_INTERNAL_ERROR;
}
//判断前一个字母是否为分隔符
if (path[strlen(path) - 1] != '/') {
if (strncat_s(fullFileName, fullFileNameLen, "/", strlen("/")) != EOK) {
return HKS_ERROR_INTERNAL_ERROR;
}
}
//在路径字符串的结尾追加字符(在路径最后追加文件名)
if (strncat_s(fullFileName, fullFileNameLen, fileName, strlen(fileName)) != EOK) {
return HKS_ERROR_INTERNAL_ERROR;
}
} else {
//路径为空的处理
if (strncpy_s(fullFileName, fullFileNameLen, fileName, strlen(fileName)) != EOK) {
return HKS_ERROR_INTERNAL_ERROR;
}
}
return HKS_SUCCESS;
}
文件全名的获取 参数含义同上个函数
//获取文件全名
static int32_t GetFullFileName(const char *path, const char *fileName, char **fullFileName)
{
uint32_t nameLen = HKS_MAX_FILE_NAME_LEN;
char *tmpFileName = (char *)HksMalloc(nameLen);
if (tmpFileName == NULL) {
return HKS_ERROR_MALLOC_FAIL;
}
(void)memset_s(tmpFileName, nameLen, 0, nameLen);
//初始化临时数组
int32_t ret = GetFileName(path, fileName, tmpFileName, nameLen);
//调用函数获取文件名
if (ret != HKS_SUCCESS) {
HKS_LOG_E("get full fileName failed");
HKS_FREE_PTR(tmpFileName);
return ret;
}
*fullFileName = tmpFileName;
return HKS_SUCCESS;
}
判断文件是否存在 参数简单,为一个文件路径和名字
//判断文件是否存在
static int32_t IsFileExist(const char *fileName)
{
if (access(fileName, F_OK) != 0) {
return HKS_ERROR_NOT_EXIST;
}
return HKS_SUCCESS;
}
文件的读取 读取一个文件,核心为read函数
//文件的读取
static uint32_t FileRead(const char *fileName, uint32_t offset, uint8_t *buf, uint32_t len)
{
(void)offset;//定义一个偏置变量
if (IsFileExist(fileName) != HKS_SUCCESS) {
//调用函数看是否存在该文件
return 0;
}
char filePath[PATH_MAX + 1] = {0};
(void)realpath(fileName, filePath);
//读取路径
if (strstr(filePath, "../") != NULL) {
HKS_LOG_E("invalid filePath, path %s", filePath);
return 0;
}
FILE *fp = fopen(filePath, "rb");
//打开文件,打开方式rb。以二进制文件打开
if (fp == NULL) {
HKS_LOG_E("failed to open file");
return 0;
//打开失败
}
uint32_t size = fread(buf, 1, len, fp);
//读取文件size
if (fclose(fp)
关注
打赏
最近更新
- 深拷贝和浅拷贝的区别(重点)
- 【Vue】走进Vue框架世界
- 【云服务器】项目部署—搭建网站—vue电商后台管理系统
- 【React介绍】 一文带你深入React
- 【React】React组件实例的三大属性之state,props,refs(你学废了吗)
- 【脚手架VueCLI】从零开始,创建一个VUE项目
- 【React】深入理解React组件生命周期----图文详解(含代码)
- 【React】DOM的Diffing算法是什么?以及DOM中key的作用----经典面试题
- 【React】1_使用React脚手架创建项目步骤--------详解(含项目结构说明)
- 【React】2_如何使用react脚手架写一个简单的页面?