ESP32-FAT文件系统使用磨损均衡存储文件笔记

基于ESP-IDF4.1

 1 /* 
 2    FAT文件系统存储文件,使用磨损均衡库wear-leveling
 3 */
 4 
 5 #include <stdlib.h>
 6 #include <stdio.h>
 7 #include <string.h>
 8 #include "esp_vfs.h"
 9 #include "esp_vfs_fat.h"
10 #include "esp_system.h"
11 
12 static const char *TAG = "example";
13 
14 // 磨损均衡处理实例
15 static wl_handle_t s_wl_handle = WL_INVALID_HANDLE;
16 
17 // 分区挂在路径
18 const char *base_path = "/spiflash";
19 
20 void app_main(void)
21 {
22     ESP_LOGI(TAG, "Mounting FAT filesystem");
23 
24     // 命名设备分区,定义base_path。如果是新分区并且没有格式化过则允许格式化分区
25     const esp_vfs_fat_mount_config_t mount_config = {
26             .max_files = 4,
27             .format_if_mount_failed = true,
28             .allocation_unit_size = CONFIG_WL_SECTOR_SIZE
29     };
30     esp_err_t err = esp_vfs_fat_spiflash_mount(base_path, "storage", &mount_config, &s_wl_handle);
31     if (err != ESP_OK) {
32         ESP_LOGE(TAG, "Failed to mount FATFS (%s)", esp_err_to_name(err));
33         return;
34     }
35     ESP_LOGI(TAG, "Opening file");
36     FILE *f = fopen("/spiflash/hello.txt", "wb"); // 读写或建立一个二进制文件
37     if (f == NULL) {
38         ESP_LOGE(TAG, "Failed to open file for writing");
39         return;
40     }
41     fprintf(f, "written using ESP-IDF %s\n", esp_get_idf_version());
42     fclose(f);
43     ESP_LOGI(TAG, "File written");
44 
45     // 打开
46     ESP_LOGI(TAG, "Reading file");
47     f = fopen("/spiflash/hello.txt", "rb"); // 读写打开一个二进制文件
48     if (f == NULL) {
49         ESP_LOGE(TAG, "Failed to open file for reading");
50         return;
51     }
52     char line[128];
53     // 从指定的流 f 读取一行,并把它存储在 line 所指向的字符串内
54     fgets(line, sizeof(line), f);
55     fclose(f);
56     // 查找换行符
57     char *pos = strchr(line, '\n');
58     if (pos) {
59         *pos = '\0'; //放置一个空字符串
60     }
61     ESP_LOGI(TAG, "Read from file: '%s'", line);
62 
63     // 卸载FAT文件系统
64     ESP_LOGI(TAG, "Unmounting FAT filesystem");
65     ESP_ERROR_CHECK( esp_vfs_fat_spiflash_unmount(base_path, s_wl_handle));
66 
67     ESP_LOGI(TAG, "Done");
68 }

 

原文:https://gitee.com/EspressifSystems/esp-idf

posted @ 2020-11-10 18:51  kerwin cui  阅读(2314)  评论(0编辑  收藏  举报