1 /* Wear levelling and FAT filesystem example.
2    This example code is in the Public Domain (or CC0 licensed, at your option.)
3 
4    Unless required by applicable law or agreed to in writing, this
5    software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
6    CONDITIONS OF ANY KIND, either express or implied.
7 
8    This sample shows how to store files inside a FAT filesystem.
9    FAT filesystem is stored in a partition inside SPI flash, using the
10    flash wear levelling library.
11 */
12 
13 #include <stdlib.h>
14 #include <stdio.h>
15 #include <string.h>
16 #include "esp_vfs.h"
17 #include "esp_vfs_fat.h"
18 #include "esp_system.h"
19 
20 static const char *TAG = "example";
21 
22 // Handle of the wear levelling library instance
23 static wl_handle_t s_wl_handle = WL_INVALID_HANDLE;
24 
25 // Mount path for the partition
26 const char *base_path = "/spiflash";
27 
app_main(void)28 void app_main(void)
29 {
30     ESP_LOGI(TAG, "Mounting FAT filesystem");
31     // To mount device we need name of device partition, define base_path
32     // and allow format partition in case if it is new one and was not formated before
33     const esp_vfs_fat_mount_config_t mount_config = {
34             .max_files = 4,
35             .format_if_mount_failed = true,
36             .allocation_unit_size = CONFIG_WL_SECTOR_SIZE
37     };
38     esp_err_t err = esp_vfs_fat_spiflash_mount(base_path, "storage", &mount_config, &s_wl_handle);
39     if (err != ESP_OK) {
40         ESP_LOGE(TAG, "Failed to mount FATFS (%s)", esp_err_to_name(err));
41         return;
42     }
43     ESP_LOGI(TAG, "Opening file");
44     FILE *f = fopen("/spiflash/hello.txt", "wb");
45     if (f == NULL) {
46         ESP_LOGE(TAG, "Failed to open file for writing");
47         return;
48     }
49     fprintf(f, "written using ESP-IDF %s\n", esp_get_idf_version());
50     fclose(f);
51     ESP_LOGI(TAG, "File written");
52 
53     // Open file for reading
54     ESP_LOGI(TAG, "Reading file");
55     f = fopen("/spiflash/hello.txt", "rb");
56     if (f == NULL) {
57         ESP_LOGE(TAG, "Failed to open file for reading");
58         return;
59     }
60     char line[128];
61     fgets(line, sizeof(line), f);
62     fclose(f);
63     // strip newline
64     char *pos = strchr(line, '\n');
65     if (pos) {
66         *pos = '\0';
67     }
68     ESP_LOGI(TAG, "Read from file: '%s'", line);
69 
70     // Unmount FATFS
71     ESP_LOGI(TAG, "Unmounting FAT filesystem");
72     ESP_ERROR_CHECK( esp_vfs_fat_spiflash_unmount(base_path, s_wl_handle));
73 
74     ESP_LOGI(TAG, "Done");
75 }
76