# FAT 文件系统

[English]

ESP-IDF 使用 FatFs 库来实现 FAT 文件系统。FatFs 库位于 `fatfs` 组件中，支持直接使用，也可以借助 C 标准库和 POSIX API 通过 VFS（虚拟文件系统）使用 FatFs 库的大多数功能。

此外，我们对 FatFs 库进行了扩展，新增了支持可插拔磁盘 I/O 调度层，从而允许在运行时将 FatFs 驱动映射到物理磁盘。

## FatFs 与 VFS 配合使用

头文件 fatfs/vfs/esp_vfs_fat.h 定义了连接 FatFs 和 VFS 的函数。

函数 `esp_vfs_fat_register()` 分配一个 `FATFS` 结构，并在 VFS 中注册特定路径前缀。如果文件路径以此前缀开头，则对此文件的后续操作将转至 FatFs API。

函数 `esp_vfs_fat_unregister_path()` 删除在 VFS 中的注册，并释放 `FATFS` 结构。

多数应用程序在使用 `esp_vfs_fat_` 函数时，采用如下步骤：

1. 调用 `esp_vfs_fat_register()`，指定：

   > - 挂载文件系统的路径前缀（例如，`"/sdcard"` 或 `"/spiflash"`）

   > - FatFs 驱动编号

   > - 一个用于接收指向 `FATFS` 结构指针的变量

2. 调用 `ff_diskio_register()`，为步骤 1 中的驱动编号注册磁盘 I/O 驱动；

3. 如需使用与传递到 `esp_vfs_fat_register()` 相同的驱动编号挂载文件系统，可调用 FatFs 函数 `f_mount()`。如果目标逻辑驱动上不存在该文件系统，`f_mount()` 将调用失败并报告 `FR_NO_FILESYSTEM` 错误。此时，应首先调用 `f_mkfs()`，在驱动上创建新的 FatFS 结构体，然后重新调用 `f_mount()`。注意，应在上述步骤之前调用 `f_fdisk()` 对 SD 卡进行分区。请参考 FatFs 文档，查看更多信息；

4. 调用 C 标准库和 POSIX API 对路径中带有步骤 1 中所述前缀的文件（例如，`"/sdcard/hello.txt"`）执行打开、读取、写入、擦除、复制等操作。文件系统默认使用 8.3 文件名 格式 (SFN)。如需使用长文件名 (LFN)，启用 CONFIG_FATFS_LONG_FILENAMES 选项。请参考 FatFs 文件系统，查看更多信息；

5. 可以直接调用 FatFs 库函数，但需要使用没有 VFS 前缀的路径，如 `"/hello.txt"`；

6. 关闭所有打开的文件；

7. 调用 FatFs 函数 `f_mount()` 并使用 NULL `FATFS*` 参数，为与上述编号相同的驱动卸载文件系统；

8. 调用 FatFs 函数 `ff_diskio_register()` 并使用 NULL `ff_diskio_impl_t*` 参数和相同的驱动编号，来释放注册的磁盘 I/O 驱动；

9. 调用 `esp_vfs_fat_unregister_path()` 并使用文件系统挂载的路径将 FatFs 从 VFS 中移除，并释放步骤 1 中分配的 `FATFS` 结构。

便捷函数 `esp_vfs_fat_sdmmc_mount()`、`esp_vfs_fat_sdspi_mount()` 和 `esp_vfs_fat_sdcard_unmount()` 对上述步骤进行了封装，并加入了对 SD 卡初始化的处理。我们将在下一章节详细介绍以上函数。

## 与 POSIX 标准的差异

1. `link()`：由于 FAT 文件系统不支持硬链接，调用 `link()` 后会复制文件内容（仅适用于 FatFs 卷上的文件）。

2. `unlink()`：当尝试删除已打开的文件时，如果启用了 `CONFIG_FATFS_FS_LOCK`，操作将失败并返回 `EBUSY`。如果未启用，则行为未定义（可能导致文件系统损坏）。

## FatFs 与 VFS 和 SD 卡配合使用

头文件 fatfs/vfs/esp_vfs_fat.h 定义了便捷函数 `esp_vfs_fat_sdmmc_mount()`、 `esp_vfs_fat_sdspi_mount()` 和 `esp_vfs_fat_sdcard_unmount()`。这些函数分别执行上一章节的步骤 1-3 和步骤 7-9，并初始化 SD 卡，但仅提供有限的错误处理功能。我们鼓励开发人员查看源代码，将更多高级功能集成到产品应用中。

便捷函数 `esp_vfs_fat_sdmmc_unmount()` 用于卸载文件系统并释放从 `esp_vfs_fat_sdmmc_mount()` 函数获取的资源。

## FatFs 与 VFS 配合使用（只读模式下）

头文件 fatfs/vfs/esp_vfs_fat.h 也定义了两个便捷函数 `esp_vfs_fat_spiflash_mount_ro()` 和 `esp_vfs_fat_spiflash_unmount_ro()`。上述两个函数分别对 FAT 只读分区执行步骤 1-3 和步骤 7-9。有些数据分区仅在工厂配置时写入一次，之后在整个硬件生命周期内都不会再有任何改动。利用上述两个函数处理这种数据分区非常方便。

## 配置选项

FatFs 组件有以下配置选项：

- CONFIG_FATFS_USE_FASTSEEK - 如果启用该选项，POSIX `lseek()` 函数将以更快的速度执行。快速查找不适用于编辑模式下的文件，所以，使用快速查找时，应在只读模式下打开（或者关闭然后重新打开）文件。

- CONFIG_FATFS_IMMEDIATE_FSYNC - 如果启用该选项，FatFs 将在每次调用 `write()`、`pwrite()`、`link()`、`truncate()` 和 `ftruncate()` 函数后，自动调用 `f_sync()` 以同步最近的文件改动。该功能提升了 FatFs 的文件一致性和文件大小报告的准确性，但频繁的磁盘操作会降低性能。

- CONFIG_FATFS_LINK_LOCK - 如果启用该选项，可保证 API 的线程安全，但如果应用程序需要快速频繁地进行小文件操作（例如将日志记录到文件），则可能有必要禁用该选项。请注意，如果禁用该选项，调用 `link()` 后的复制操作将是非原子的，此时如果在不同任务中对同一卷上的大文件调用 `link()`，则无法确保线程安全。

以下选项用于设置 FatFs 文件系统计算和报告空闲空间的策略：

- CONFIG_FATFS_DONT_TRUST_FREE_CLUSTER_CNT – 如果设置为 1，将忽略空闲簇计数。默认值为 0。

- CONFIG_FATFS_DONT_TRUST_LAST_ALLOC – 如果设置为 1，将忽略上次分配的簇号。默认值为 0。

备注

将这两个选项设为 1 可能会提高 `f_getfree()` 输出的准确性，但性能会下降，例如，可能需要执行完整的 FAT 扫描。

## FatFs 磁盘 I/O 层

我们对 FatFs API 函数进行了扩展，实现了运行期间注册磁盘 I/O 驱动。

上述 API 为 SD/MMC 卡提供了磁盘 I/O 函数实现方式，可使用 `ff_diskio_register_sdmmc()` 函数注册指定的 FatFs 驱动编号。

void ff_diskio_register(BYTE pdrv, const ff_diskio_impl_t *discio_impl)

  Register or unregister diskio driver for given drive number.

  When FATFS library calls one of disk_xxx functions for driver number pdrv, corresponding function in discio_impl for given pdrv will be called.

  参数:

    - pdrv -- drive number

    - discio_impl -- pointer to ff_diskio_impl_t structure with diskio functions or NULL to unregister and free previously registered drive

struct ff_diskio_impl_t

  Structure of pointers to disk IO driver functions.

  See FatFs documentation for details about these functions

  Public Members

  DSTATUS (*init)(unsigned char pdrv)

    disk initialization function

  DSTATUS (*status)(unsigned char pdrv)

    disk status check function

  DRESULT (*read)(unsigned char pdrv, unsigned char *buff, uint32_t sector, unsigned count)

    sector read function

  DRESULT (*write)(unsigned char pdrv, const unsigned char *buff, uint32_t sector, unsigned count)

    sector write function

  DRESULT (*ioctl)(unsigned char pdrv, unsigned char cmd, void *buff)

    function to get info about disk and do some misc operations

void ff_diskio_register_sdmmc(unsigned char pdrv, sdmmc_card_t *card)

  Register SD/MMC diskio driver

  参数:

    - pdrv -- drive number

    - card -- pointer to sdmmc_card_t structure describing a card; card should be initialized before calling f_mount.

esp_err_t ff_diskio_register_wl_partition(unsigned char pdrv, wl_handle_t flash_handle)

  Register spi flash partition

  参数:

    - pdrv -- drive number

    - flash_handle -- handle of the wear levelling partition.

esp_err_t ff_diskio_register_raw_partition(unsigned char pdrv, const esp_partition_t *part_handle)

  Register spi flash partition

  参数:

    - pdrv -- drive number

    - part_handle -- pointer to raw flash partition.

## FatFs 分区生成器

我们为 FatFs (wl_fatfsgen.py) 提供了分区生成器，该生成器集成在构建系统中，方便用户在自己的项目中使用。

该生成器可以在主机上创建文件系统镜像，并用指定的主机文件夹内容对其进行填充。

该脚本是建立在分区生成器的基础上 (fatfsgen.py)，目前除了可以生成分区外，也可以初始化损耗均衡。

目前的最新版本支持短文件名、长文件名、FAT12 和 FAT16。长文件名的上限是 255 个字符，文件名中可以包含多个 `.` 字符以及其他字符，如 `+`、`,`、`;`、`=`、`[` and `]` 等。

如需进一步了解 FatFs 分区生成器或分区分析器，请查看 Generating and parsing FAT partition on host。

### 构建系统中使用 FatFs 分区生成器

通过调用 `fatfs_create_partition_image` 可以直接从 CMake 构建系统中调用 FatFs 分区生成器:

    fatfs_create_spiflash_image(<partition> <base_dir> [FLASH_IN_PROJECT])

如果不希望在生成分区时使用损耗均衡，可以使用 `fatfs_create_rawflash_image`:

    fatfs_create_rawflash_image(<partition> <base_dir> [FLASH_IN_PROJECT])

`fatfs_create_spiflash_image` 以及 `fatfs_create_rawflash_image` 必须从项目的 CMakeLists.txt 中调用。

如果决定使用 `fatfs_create_rawflash_image` （不支持损耗均衡），请注意它仅支持在设备中以只读模式安装。

该函数的参数如下：

1. partition - 分区的名称，需要在分区表中定义（如 storage/fatfs/fatfsgen/partitions_example.csv）。

2. base_dir - 目录名称，该目录会被编码为 FatFs 分区，也可以选择将其被烧录进设备。但注意必须在分区表中指定合适的分区大小。

3. `FLASH_IN_PROJECT` 标志 - 可选参数，用户可以通过指定 `FLASH_IN_PROJECT`，选择在执行 `idf.py flash -p <PORT>` 时让分区镜像自动与应用程序二进制文件、分区表等一同烧录进设备。

4. `PRESERVE_TIME` 标志 - 可选参数，用户可强制让目标镜像保留源文件夹的时间戳。如果不保留，每个目标镜像的时间戳都将设置为 FATFS 默认初始时间（1980 年 1 月 1 日）。

5. `ONE_FAT` 标志 - 可选参数，支持生成仅包含单个 FAT（文件分配表）的 FATFS 卷。与包含两个 FAT 的 FATFS 卷相比，这样做可以拥有相对较大的可用空间（通过 `FAT 使用的扇区数 * 扇区大小` 计算），但会增加 FATFS 卷损坏的风险。

例如:

    fatfs_create_partition_image(my_fatfs_partition my_folder FLASH_IN_PROJECT)

没有指定 FLASH_IN_PROJECT 时也可以生成分区镜像，但是用户需要使用 `esptool` 或自定义的构建系统目标对其手动烧录。

相关示例请查看 storage/fatfs/fatfsgen。

## FatFs 分区分析器

我们为 FatFs 提供分区分析器 (fatfsparse.py)。

该分析器为 FatFs 分区生成器 (fatfsgen.py) 的逆向工具，可以根据 FatFs 镜像在主机上生成文件夹结构。

可以使用:

    ./fatfsparse.py [-h] [--wl-layer {detect,enabled,disabled}] [--verbose] fatfs_image.img

生成文件夹结构之前，参数 --verbose 将根据 FatFs 镜像的引导扇区在终端打印详细信息。

## FATFS 最小分区大小及限制

FATFS 组件支持 FAT12、FAT16 和 FAT32 文件系统类型。文件系统类型取决于卷上簇的数量（簇数通过数据扇区数量除以每簇包含的扇区数计算得出）。最小分区大小由分配给 FAT 表、根目录和数据簇的扇区数量决定。

- 对于 4096 字节的扇区，启用损耗均衡的 FAT 分区大小最小支持 32 KB。对于 512 字节的扇区，最小分区大小取决于损耗均衡的配置：性能模式下，最小支持 20 KB，安全模式下最小支持 28 KB（需要额外的 2 个扇区）。

- 启用了损耗均衡的分区会预留 4 个扇区用于损耗均衡操作。此外，FATFS 本身也会使用 4 个扇区，分别为 1 个保留扇区、1 个 FAT 扇区、1 个根目录扇区和 1 个数据扇区。

- 增加分区大小将分配更多的数据扇区，提供更大的存储空间。

- 对小于 528 KB 的分区，将分配 1 个根目录扇区；对于更大的分区，将分配 4 个根目录扇区。

- 默认会创建两个 FAT 扇区，因此分区大小会增加一个扇区来容纳这个额外的 FAT 扇区。如要启用单个 FAT 扇区，可以在 struct esp_vfs_fat_mount_config_t 中（参见 fatfs/vfs/esp_vfs_fat.h）设置 use_one_fat 选项。启用此选项后，最小分区大小可减少至 32 KB。

- 计算损耗均衡分区大小的一般公式为:

      partition_size = 损耗均衡扇区数 * FLASH_SEC_SIZE + FATFS 分区扇区数量 * FAT_SEC_SIZE

  其中：

  - 损耗均衡扇区数固定为 4 个

  - FLASH_SEC_SIZE 为 4096 字节

  - FATFS 分区扇区包括：1 个保留扇区 + FAT 扇区 + 根目录扇区 + 数据扇区

  - FAT_SEC_SIZE 根据不同的配置，可以是 512 字节或 4096 字节

- 对于未启用损耗均衡、扇区大小为 512 字节的只读分区，最小分区大小可减少至 2 KB。

更多详情请参考 文件系统注意事项。

## 应用示例

- storage/fatfs/getting_started 演示了如何使用 FatFS 在 SPI flash 上存储永久数据的基本设置，包括挂载文件系统、打开文件、执行基本的读写操作以及卸载文件系统。

- storage/fatfs/fs_operations 演示了更全面的 FatFS 操作，包括读取和写入文件、创建、移动和删除文件及目录，以及检查文件详细信息。

- storage/fatfs/ext_flash 演示了如何操作使用 FatFS 格式化的外部 SPI flash，包括初始化 SPI 总线、配置 flash、将其注册为分区以及执行读写操作。

## 高级 API 参考

### Header File

- components/fatfs/vfs/esp_vfs_fat.h

- This header file can be included with:

  >     #include "esp_vfs_fat.h"

- This header file is a part of the API provided by the `fatfs` component. To declare that your component depends on `fatfs`, add the following to your CMakeLists.txt:

  >     REQUIRES fatfs

  > or

  >     PRIV_REQUIRES fatfs

### Functions

esp_err_t esp_vfs_fat_register(const esp_vfs_fat_conf_t *conf, FATFS **out_fs)

  Register FATFS with VFS component.

  This function registers given FAT drive in VFS, at the specified base path. Input arguments are held in esp_vfs_fat_conf_t structure. If only one drive is used, fat_drive argument can be an empty string. Refer to FATFS library documentation on how to specify FAT drive. This function also allocates FATFS structure which should be used for f_mount call.

  备注

  This function doesn't mount the drive into FATFS, it just connects POSIX and C standard library IO function with FATFS. You need to mount desired drive into FATFS separately.

  参数:

    - conf -- pointer to esp_vfs_fat_conf_t configuration structure

    - out_fs -- [out] pointer to FATFS structure which can be used for FATFS f_mount call is returned via this argument.

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_STATE if esp_vfs_fat_register was already called

    - ESP_ERR_NO_MEM if not enough memory or too many VFSes already registered

esp_err_t esp_vfs_fat_unregister_path(const char *base_path)

  Un-register FATFS from VFS.

  备注

  FATFS structure returned by esp_vfs_fat_register is destroyed after this call. Make sure to call f_mount function to unmount it before calling esp_vfs_fat_unregister_ctx. Difference between this function and the one above is that this one will release the correct drive, while the one above will release the last registered one

  参数:

    base_path -- path prefix where FATFS is registered. This is the same used when esp_vfs_fat_register was called

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_STATE if FATFS is not registered in VFS

esp_err_t esp_vfs_fat_sdmmc_mount(const char *base_path, const sdmmc_host_t *host_config, const void *slot_config, const esp_vfs_fat_mount_config_t *mount_config, sdmmc_card_t **out_card)

  Convenience function to get FAT filesystem on SD card registered in VFS.

  This is an all-in-one function which does the following:

  - initializes SDMMC driver or SPI driver with configuration in host_config

  - initializes SD card with configuration in slot_config

  - mounts FAT partition on SD card using FATFS library, with configuration in mount_config

  - registers FATFS library with VFS, with prefix given by base_prefix variable

  This function is intended to make example code more compact. For real world applications, developers should implement the logic of probing SD card, locating and mounting partition, and registering FATFS in VFS, with proper error checking and handling of exceptional conditions.

  备注

  Use this API to mount a card through SDSPI is deprecated. Please call `esp_vfs_fat_sdspi_mount()` instead for that case.

  参数:

    - base_path -- path where partition should be registered (e.g. "/sdcard")

    - host_config -- Pointer to structure describing SDMMC host. When using SDMMC peripheral, this structure can be initialized using SDMMC_HOST_DEFAULT() macro. When using SPI peripheral, this structure can be initialized using SDSPI_HOST_DEFAULT() macro.

    - slot_config -- Pointer to structure with slot configuration. For SDMMC peripheral, pass a pointer to sdmmc_slot_config_t structure initialized using SDMMC_SLOT_CONFIG_DEFAULT.

    - mount_config -- pointer to structure with extra parameters for mounting FATFS

    - out_card -- [out] pointer to the card information structure will be returned via this argument

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_ARG if any of the arguments is NULL

    - ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called

    - ESP_ERR_NO_MEM if memory can not be allocated

    - ESP_FAIL if partition can not be mounted

    - other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers

esp_err_t esp_vfs_fat_sdspi_mount(const char *base_path, const sdmmc_host_t *host_config_input, const sdspi_device_config_t *slot_config, const esp_vfs_fat_mount_config_t *mount_config, sdmmc_card_t **out_card)

  Convenience function to get FAT filesystem on SD card registered in VFS.

  This is an all-in-one function which does the following:

  - initializes an SPI Master device based on the SPI Master driver with configuration in slot_config, and attach it to an initialized SPI bus.

  - initializes SD card with configuration in host_config_input

  - mounts FAT partition on SD card using FATFS library, with configuration in mount_config

  - registers FATFS library with VFS, with prefix given by base_prefix variable

  This function is intended to make example code more compact. For real world applications, developers should implement the logic of probing SD card, locating and mounting partition, and registering FATFS in VFS, with proper error checking and handling of exceptional conditions.

  备注

  This function try to attach the new SD SPI device to the bus specified in host_config. Make sure the SPI bus specified in `host_config->slot` have been initialized by `spi_bus_initialize()` before.

  参数:

    - base_path -- path where partition should be registered (e.g. "/sdcard")

    - host_config_input -- Pointer to structure describing SDMMC host. This structure can be initialized using SDSPI_HOST_DEFAULT() macro.

    - slot_config -- Pointer to structure with slot configuration. For SPI peripheral, pass a pointer to sdspi_device_config_t structure initialized using SDSPI_DEVICE_CONFIG_DEFAULT().

    - mount_config -- pointer to structure with extra parameters for mounting FATFS

    - out_card -- [out] Pointer to the card information structure will be returned via this argument. It is suggested to hold this handle and use it to unmount the card later if needed. Otherwise it's not suggested to use more than one card at the same time and unmount one of them in your application.

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_ARG if any of the arguments is NULL

    - ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount was already called

    - ESP_ERR_NO_MEM if memory can not be allocated

    - ESP_FAIL if partition can not be mounted

    - other error codes from SDMMC or SPI drivers, SDMMC protocol, or FATFS drivers

esp_err_t esp_vfs_fat_sdcard_unmount(const char *base_path, sdmmc_card_t *card)

  Unmount an SD card from the FAT filesystem and release resources acquired using `esp_vfs_fat_sdmmc_mount()` or `esp_vfs_fat_sdspi_mount()`

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_ARG if the card argument is unregistered

    - ESP_ERR_INVALID_STATE if esp_vfs_fat_sdmmc_mount hasn't been called

esp_err_t esp_vfs_fat_sdcard_format_cfg(const char *base_path, sdmmc_card_t *card, esp_vfs_fat_mount_config_t *cfg)

  Format FAT filesystem with given configuration.

  备注

  This API should be only called when the FAT is already mounted.

  参数:

    - base_path -- Path where partition should be registered (e.g. "/sdcard")

    - card -- Pointer to the card handle, which should be initialised by calling `esp_vfs_fat_sdspi_mount` first

    - cfg -- Pointer to structure with extra parameters for formatting FATFS (only relevant fields are used). If NULL, the previous configuration will be used.

  返回:

    - ESP_OK

    - ESP_ERR_INVALID_STATE: FAT partition isn't mounted, call esp_vfs_fat_sdmmc_mount or esp_vfs_fat_sdspi_mount first

    - ESP_ERR_NO_MEM: if memory can not be allocated

    - ESP_FAIL: fail to format it, or fail to mount back

esp_err_t esp_vfs_fat_sdcard_format(const char *base_path, sdmmc_card_t *card)

  Format FAT filesystem.

  备注

  This API should be only called when the FAT is already mounted.

  参数:

    - base_path -- Path where partition should be registered (e.g. "/sdcard")

    - card -- Pointer to the card handle, which should be initialised by calling `esp_vfs_fat_sdspi_mount` first

  返回:

    - ESP_OK

    - ESP_ERR_INVALID_STATE: FAT partition isn't mounted, call esp_vfs_fat_sdmmc_mount or esp_vfs_fat_sdspi_mount first

    - ESP_ERR_NO_MEM: if memory can not be allocated

    - ESP_FAIL: fail to format it, or fail to mount back

esp_err_t esp_vfs_fat_spiflash_mount_rw_wl(const char *base_path, const char *partition_label, const esp_vfs_fat_mount_config_t *mount_config, wl_handle_t *wl_handle)

  Convenience function to initialize FAT filesystem in SPI flash and register it in VFS.

  This is an all-in-one function which does the following:

  - finds the partition with defined partition_label. Partition label should be configured in the partition table.

  - initializes flash wear levelling library on top of the given partition

  - mounts FAT partition using FATFS library on top of flash wear levelling library

  - registers FATFS library with VFS, with prefix given by base_prefix variable

  This function is intended to make example code more compact.

  参数:

    - base_path -- path where FATFS partition should be mounted (e.g. "/spiflash")

    - partition_label -- label of the partition which should be used

    - mount_config -- pointer to structure with extra parameters for mounting FATFS

    - wl_handle -- [out] wear levelling driver handle

  返回:

    - ESP_OK on success

    - ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with given label

    - ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_rw_wl was already called

    - ESP_ERR_NO_MEM if memory can not be allocated

    - ESP_FAIL if partition can not be mounted

    - other error codes from wear levelling library, SPI flash driver, or FATFS drivers

esp_err_t esp_vfs_fat_spiflash_unmount_rw_wl(const char *base_path, wl_handle_t wl_handle)

  Unmount FAT filesystem and release resources acquired using esp_vfs_fat_spiflash_mount_rw_wl.

  参数:

    - base_path -- path where partition should be registered (e.g. "/spiflash")

    - wl_handle -- wear levelling driver handle returned by esp_vfs_fat_spiflash_mount_rw_wl

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_rw_wl hasn't been called

esp_err_t esp_vfs_fat_spiflash_format_cfg_rw_wl(const char *base_path, const char *partition_label, esp_vfs_fat_mount_config_t *cfg)

  Format FAT filesystem with given configuration.

  备注

  This API can be called when the FAT is mounted / not mounted. If this API is called when the FAT isn't mounted (by calling esp_vfs_fat_spiflash_mount_rw_wl), this API will first mount the FAT then format it, then restore back to the original state.

  参数:

    - base_path -- Path where partition should be registered (e.g. "/spiflash")

    - partition_label -- Label of the partition which should be used

    - cfg -- Pointer to structure with extra parameters for formatting FATFS (only relevant fields are used). If NULL and mounted the previous configuration will be used. If NULL and unmounted the default configuration will be used.

  返回:

    - ESP_OK

    - ESP_ERR_NO_MEM: if memory can not be allocated

    - Other errors from esp_vfs_fat_spiflash_mount_rw_wl

esp_err_t esp_vfs_fat_spiflash_format_rw_wl(const char *base_path, const char *partition_label)

  Format FAT filesystem.

  备注

  This API can be called when the FAT is mounted / not mounted. If this API is called when the FAT isn't mounted (by calling esp_vfs_fat_spiflash_mount_rw_wl), this API will first mount the FAT then format it, then restore back to the original state.

  参数:

    - base_path -- Path where partition should be registered (e.g. "/spiflash")

    - partition_label -- Label of the partition which should be used

  返回:

    - ESP_OK

    - ESP_ERR_NO_MEM: if memory can not be allocated

    - Other errors from esp_vfs_fat_spiflash_mount_rw_wl

esp_err_t esp_vfs_fat_spiflash_mount_ro(const char *base_path, const char *partition_label, const esp_vfs_fat_mount_config_t *mount_config)

  Convenience function to initialize read-only FAT filesystem and register it in VFS.

  This is an all-in-one function which does the following:

  - finds the partition with defined partition_label. Partition label should be configured in the partition table.

  - mounts FAT partition using FATFS library

  - registers FATFS library with VFS, with prefix given by base_prefix variable

  备注

  Wear levelling is not used when FAT is mounted in read-only mode using this function.

  参数:

    - base_path -- path where FATFS partition should be mounted (e.g. "/spiflash")

    - partition_label -- label of the partition which should be used

    - mount_config -- pointer to structure with extra parameters for mounting FATFS

  返回:

    - ESP_OK on success

    - ESP_ERR_NOT_FOUND if the partition table does not contain FATFS partition with given label

    - ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_ro was already called for the same partition

    - ESP_ERR_NO_MEM if memory can not be allocated

    - ESP_FAIL if partition can not be mounted

    - other error codes from SPI flash driver, or FATFS drivers

esp_err_t esp_vfs_fat_spiflash_unmount_ro(const char *base_path, const char *partition_label)

  Unmount FAT filesystem and release resources acquired using esp_vfs_fat_spiflash_mount_ro.

  参数:

    - base_path -- path where partition should be registered (e.g. "/spiflash")

    - partition_label -- label of partition to be unmounted

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_STATE if esp_vfs_fat_spiflash_mount_ro hasn't been called

esp_err_t esp_vfs_fat_info(const char *base_path, uint64_t *out_total_bytes, uint64_t *out_free_bytes)

  Get information for FATFS partition.

  参数:

    - base_path -- Base path of the partition examined (e.g. "/spiflash")

    - out_total_bytes -- [out] Size of the file system

    - out_free_bytes -- [out] Free bytes available in the file system

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_STATE if partition not found

    - ESP_FAIL if another FRESULT error (saved in errno)

esp_err_t esp_vfs_fat_create_contiguous_file(const char *base_path, const char *full_path, uint64_t size, bool alloc_now)

  Create a file with contiguous space at given path.

  备注

  The file cannot exist before calling this function (or the file size has to be 0) For more information see documentation for `f_expand` from FATFS library

  参数:

    - base_path -- Base path of the partition examined (e.g. "/spiflash")

    - full_path -- Full path of the file (e.g. "/spiflash/ABC.TXT")

    - size -- File size expanded to, number of bytes in size to prepare or allocate for the file

    - alloc_now -- True == allocate space now, false == prepare to allocate – see `f_expand` from FATFS

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_ARG if invalid arguments (e.g. any of arguments are NULL or size lower or equal to 0)

    - ESP_ERR_INVALID_STATE if partition not found

    - ESP_FAIL if another FRESULT error (saved in errno)

esp_err_t esp_vfs_fat_test_contiguous_file(const char *base_path, const char *full_path, bool *is_contiguous)

  Test if a file is contiguous in the FAT filesystem.

  参数:

    - base_path -- Base path of the partition examined (e.g. "/spiflash")

    - full_path -- Full path of the file (e.g. "/spiflash/ABC.TXT")

    - is_contiguous -- [out] True == allocate space now, false == prepare to allocate – see `f_expand` from FATFS

  返回:

    - ESP_OK on success

    - ESP_ERR_INVALID_ARG if invalid arguments (e.g. any of arguments are NULL)

    - ESP_ERR_INVALID_STATE if partition not found

    - ESP_FAIL if another FRESULT error (saved in errno)

### Structures

struct esp_vfs_fat_conf_t

  Configuration structure for esp_vfs_fat_register.

  Public Members

  const char *base_path

    Path prefix where FATFS should be registered,

  const char *fat_drive

    FATFS drive specification; if only one drive is used, can be an empty string.

  size_t max_files

    Maximum number of files which can be open at the same time.

struct esp_vfs_fat_mount_config_t

  Configuration arguments for esp_vfs_fat_sdmmc_mount and esp_vfs_fat_spiflash_mount_rw_wl functions.

  Public Members

  bool format_if_mount_failed

    If FAT partition can not be mounted, and this parameter is true, create partition table and format the filesystem.

  int max_files

    Max number of open files.

  size_t allocation_unit_size

    If format_if_mount_failed is set, and mount fails, format the card with given allocation unit size. Must be a power of 2, between sector size and 128 * sector size. For SD cards, sector size is always 512 bytes. For wear_levelling, sector size is determined by CONFIG_WL_SECTOR_SIZE option.

    Using larger allocation unit size will result in higher read/write performance and higher overhead when storing small files.

    Setting this field to 0 will result in allocation unit set to the sector size.

  bool disk_status_check_enable

    Enables real ff_disk_status function implementation for SD cards (ff_sdmmc_status). Possibly slows down IO performance.

    Try to enable if you need to handle situations when SD cards are not unmounted properly before physical removal or you are experiencing issues with SD cards.

    Doesn't do anything for other memory storage media.

  bool use_one_fat

    Use 1 FAT (File Allocation Tables) instead of 2. This decreases reliability, but makes more space available (usually only one sector). Note that this option has effect only when the filesystem is formatted. When mounting an already-formatted partition, the actual number of FATs may be different.

### Macros

VFS_FAT_MOUNT_DEFAULT_CONFIG()

### Type Definitions

typedef PARTITION esp_vfs_fat_pdrv_part_t

typedef LBA_t esp_vfs_fat_drive_divide_arr_t[4]

  For example:

  `{100, 0, 0, 0}` will create a single partition with 100% of the drive space. `{50, 50, 0, 0}` will create two partitions, first with 50% of the drive space and second with the remaining 50%. `{0x10000000, 0x10000000, 0x10000000, 0}` will create three partitions, each with a size of 256 MiB, leaving remaining space non-allocated.

  备注

  When the value of item is less than or equal to 100, it specifies the partition size in percentage of the entire drive space. When it is larger than 100, it specifies number of sectors. The partition map table is terminated by a zero, 4th partition in MBR format or no remaining space for next allocation. If the specified size is larger than remaining space on the drive, the partition is truncated at end of the drive.

typedef esp_vfs_fat_mount_config_t esp_vfs_fat_sdmmc_mount_config_t

### Enumerations

enum vfs_fat_x_ctx_flags_t

  Values:

  enumerator FORMATTED_DURING_LAST_MOUNT

此文档对您有帮助吗？

- 反馈已收到，谢谢！
- 如果您有其他意见，欢迎填写乐鑫文档反馈表。

- 我们重视您的反馈。
- 您可以填写乐鑫文档反馈表告诉我们如何改进该文档。