极简文件列表

简介

单片机里搭建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;
}
相关推荐
another heaven9 小时前
【C/C++ 第一次跨越(上):用 C++11/14 停止制造新的旧代码】
c语言·c++·制造
another heaven1 天前
【C/C++ Ranges 是零开销抽象吗?拆开管道、惰性求值和编译期膨胀】
c语言·开发语言·c++
Code_Solitude1 天前
C语言动态内存 + 柔性数组 + 数组名退化
c语言·算法·柔性数组
Zwawa1 天前
让屏幕动起来:OLED动画效果,丝滑光标、帧动画和一只贪吃蛇
c语言·单片机·嵌入式
꧁细听勿语情꧂1 天前
直接选择排序,堆排序,冒泡排序,递归快速排序、hoare版本、挖坑法、lomuto前后指针,非递归快速排序
c语言·开发语言·数据结构·算法
§ꦿCFོ༉2 天前
嵌入式八股文—C语言入门学习(四)
c语言·开发语言·学习
Severus_black2 天前
【C++初阶】Stack、Queue算法题大练兵!
c语言·c++·算法·stl
唐青枫2 天前
C 语言 strcpy() 用法详解与实战 Demo
c语言
程序猿打工仔2 天前
计算机基础(C语言)考编、专技岗
c语言·开发语言·算法
꧁细听勿语情꧂2 天前
二叉树余题,排序、直接插入排序、希尔排序
c语言·开发语言·数据结构·算法