极简文件列表

简介

单片机里搭建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;
}
相关推荐
JoyCheung-21 小时前
Free底层是怎么释放内存的
linux·c语言
阿华hhh1 天前
项目(购物商城)
linux·服务器·c语言·c++
方便面不加香菜1 天前
基于顺序表实现通讯录项目
c语言·数据结构
无限进步_1 天前
【数据结构&C语言】对称二叉树的递归之美:镜像世界的探索
c语言·开发语言·数据结构·c++·算法·github·visual studio
Eternity∞1 天前
基于Linux系统vim编译器情况下的C语言学习
linux·c语言·开发语言·学习·vim
HUST1 天前
C语言第十一讲: 深入理解指针(1)
c语言·开发语言
SoveTingღ1 天前
【C语言】什么是野指针?
c语言·指针·嵌入式软件
lowhot1 天前
C语言UI框架
c语言·开发语言·笔记·ui
ベadvance courageouslyミ1 天前
项目一(线程邮箱)
c语言·线程·makefile·进程间通信·线程邮箱
Herbert_hwt1 天前
C语言表达式求值详解:从原理到实战的完整指南
c语言