极简文件列表

简介

单片机里搭建webserver,储存的资源需要用文件系统。如果使用fatfs之类的,体积太庞大,所以需要自己搭建一个按名访问的极简文件系统。

文件对象结构

c 复制代码
typedef struct {
    char *name;
    char *content;
}File_Item_t;
  • name:文件名
  • content:文件内容

文件存储和注册

c 复制代码
/// @brief File List
File_Item_t File_List[config_MAX_FileItem] = {0};

/// @brief register file name and file content to FileSystem
/// @param i :index
/// @param name :file name
/// @param content :file content, could be stored in flash or in ram
void SF_register(uint16_t i, char *name, char *content)
{
    if(i >= config_MAX_FileItem)
        return;
    File_List[i].name = name;
    File_List[i].content = content;
}

文件按名访问

按名访问只做到获取文件内容头指针,对文件的读写要自己建立缓冲区进行读写,文件长度限制要注意。

c 复制代码
/// @brief find file by name
/// @param file_name :file name
/// @param len :file name length, should be identical with name length in filesystem
/// @return file item pointer(File_Item_t *)
File_Item_t *SF_find(char *file_name, uint8_t len)
{
    if(len > config_MAX_Namelen)
        return 0;
    for(uint16_t i = 0; i < config_MAX_FileItem; i++)
    {
        if((strlen(file_name) == strlen(File_List[i].name)) && 
            (!memcmp(file_name, File_List[i].name, strlen(file_name))))
        {
            return &(File_List[i]);
        }
    }
    return 0;
}

测试

c 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include "Simple_Filesystem.h"

const char *file0_name = "boot0.bin";
const char *file0_content = "bin0bin0bin0bin0bin0bin0bin0bin0bin0";
const char *file1_name = "boot1.bin";
const char *file1_content = "bin1bin1bin1bin1bin1bin1bin1bin1bin1";

int main(int argc, char **argv)
{
    SF_register(0, (void *)file0_name, (void *)file0_content);
    SF_register(1, (void *)file1_name, (void *)file1_content);

    File_Item_t *filep = NULL;
    filep = SF_find("boot0.bin", strlen("boot0.bin"));
    if(filep)
        printf("file %s = %s\r\n",filep->name, filep->content);
    filep = SF_find("boot1.bin", strlen("boot1.bin"));
    if(filep)
        printf("file %s = %s\r\n",filep->name, filep->content);

    return 0;
}
相关推荐
祈安_3 天前
C语言内存函数
c语言·后端
norlan_jame5 天前
C-PHY与D-PHY差异
c语言·开发语言
czy87874755 天前
除了结构体之外,C语言中还有哪些其他方式可以模拟C++的面向对象编程特性
c语言
m0_531237175 天前
C语言-数组练习进阶
c语言·开发语言·算法
Z9fish5 天前
sse哈工大C语言编程练习23
c语言·数据结构·算法
代码无bug抓狂人5 天前
C语言之单词方阵——深搜(很好的深搜例题)
c语言·开发语言·算法·深度优先
CodeJourney_J5 天前
从“Hello World“ 开始 C++
c语言·c++·学习
枫叶丹45 天前
【Qt开发】Qt界面优化(七)-> Qt样式表(QSS) 样式属性
c语言·开发语言·c++·qt
with-the-flow5 天前
从数学底层的底层原理来讲 random 的函数是怎么实现的
c语言·python·算法
Sunsets_Red5 天前
P8277 [USACO22OPEN] Up Down Subsequence P 题解
c语言·c++·算法·c#·学习方法·洛谷·信息学竞赛