1
8
9
16
17
18
19
20
21
22
23
29
30
31
32
33
34
44
45
46
55
56
57
58
65
66
67
79
80
81
82
83
84
88
89
90
91
92
93
94
98
99
100
101
105
106
107
108
109
113
114
115
116
117
118
121
122
123
124
125
126
/* ... */
#include <stdio.h>
#include <string.h>
#include <sys/unistd.h>
#include <sys/stat.h>
#include "esp_err.h"
#include "esp_log.h"
#include "esp_spiffs.h"7 includes
static const char *TAG = "example";
void app_main(void)
{
ESP_LOGI(TAG, "Initializing SPIFFS");
esp_vfs_spiffs_conf_t conf = {
.base_path = "/spiffs",
.partition_label = NULL,
.max_files = 5,
.format_if_mount_failed = true
}{...};
esp_err_t ret = esp_vfs_spiffs_register(&conf);
if (ret != ESP_OK) {
if (ret == ESP_FAIL) {
ESP_LOGE(TAG, "Failed to mount or format filesystem");
}{...} else if (ret == ESP_ERR_NOT_FOUND) {
ESP_LOGE(TAG, "Failed to find SPIFFS partition");
}{...} else {
ESP_LOGE(TAG, "Failed to initialize SPIFFS (%s)", esp_err_to_name(ret));
}{...}
return;
}{...}
#ifdef CONFIG_EXAMPLE_SPIFFS_CHECK_ON_START
ESP_LOGI(TAG, "Performing SPIFFS_check().");
ret = esp_spiffs_check(conf.partition_label);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "SPIFFS_check() failed (%s)", esp_err_to_name(ret));
return;
}{...} else {
ESP_LOGI(TAG, "SPIFFS_check() successful");
}{...}
#endif/* ... */
size_t total = 0, used = 0;
ret = esp_spiffs_info(conf.partition_label, &total, &used);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to get SPIFFS partition information (%s). Formatting...", esp_err_to_name(ret));
esp_spiffs_format(conf.partition_label);
return;
}{...} else {
ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used);
}{...}
if (used > total) {
ESP_LOGW(TAG, "Number of used bytes cannot be larger than total. Performing SPIFFS_check().");
ret = esp_spiffs_check(conf.partition_label);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "SPIFFS_check() failed (%s)", esp_err_to_name(ret));
return;
}{...} else {
ESP_LOGI(TAG, "SPIFFS_check() successful");
}{...}
}{...}
ESP_LOGI(TAG, "Opening file");
FILE* f = fopen("/spiffs/hello.txt", "w");
if (f == NULL) {
ESP_LOGE(TAG, "Failed to open file for writing");
return;
}{...}
fprintf(f, "Hello World!\n");
fclose(f);
ESP_LOGI(TAG, "File written");
struct stat st;
if (stat("/spiffs/foo.txt", &st) == 0) {
unlink("/spiffs/foo.txt");
}{...}
ESP_LOGI(TAG, "Renaming file");
if (rename("/spiffs/hello.txt", "/spiffs/foo.txt") != 0) {
ESP_LOGE(TAG, "Rename failed");
return;
}{...}
ESP_LOGI(TAG, "Reading file");
f = fopen("/spiffs/foo.txt", "r");
if (f == NULL) {
ESP_LOGE(TAG, "Failed to open file for reading");
return;
}{...}
char line[64];
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_vfs_spiffs_unregister(conf.partition_label);
ESP_LOGI(TAG, "SPIFFS unmounted");
}{ ... }