1
6
7
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
33
34
35
36
40
41
42
43
44
45
46
47
48
53
54
55
56
57
58
59
60
61
62
63
67
68
69
70
71
72
73
74
75
78
79
80
81
82
83
84
85
86
87
/* ... */
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "esp_vfs.h"
#include "esp_vfs_fat.h"
#include "sdkconfig.h"6 includes
static const char *TAG = "example";
const char *base_path = "/spiflash";
static wl_handle_t s_wl_handle = WL_INVALID_HANDLE;
void app_main(void)
{
ESP_LOGI(TAG, "Mounting FAT filesystem");
const esp_vfs_fat_mount_config_t mount_config = {
.max_files = 4,
.format_if_mount_failed = true,
.allocation_unit_size = CONFIG_WL_SECTOR_SIZE,
.use_one_fat = false,
}{...};
esp_err_t err = esp_vfs_fat_spiflash_mount_rw_wl(base_path, "storage", &mount_config, &s_wl_handle);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to mount FATFS (%s)", esp_err_to_name(err));
return;
}{...}
ESP_LOGI(TAG, "Filesystem mounted");
ESP_LOGI(TAG, "Opening file");
const char *filename = "/spiflash/example.txt";
FILE *f = fopen(filename, "wb");
if (f == NULL) {
perror("fopen");
ESP_LOGE(TAG, "Failed to open file for writing");
return;
}{...}
fprintf(f, "Hello World!\n");
fclose(f);
ESP_LOGI(TAG, "File written");
ESP_LOGI(TAG, "Reading file");
f = fopen(filename, "r");
if (f == NULL) {
ESP_LOGE(TAG, "Failed to open file for reading");
return;
}{...}
char line[128];
fgets(line, sizeof(line), f);
fclose(f);
char *pos = strchr(line, '\n');
if (pos) {
*pos = '\0';
}{...}
ESP_LOGI(TAG, "Read from file: '%s'", line);
ESP_LOGI(TAG, "Unmounting FAT filesystem");
ESP_ERROR_CHECK(esp_vfs_fat_spiflash_unmount_rw_wl(base_path, s_wl_handle));
ESP_LOGI(TAG, "Done");
}{ ... }