1
7
8
16
17
18
19
20
21
22
23
29
30
31
32
33
34
44
45
46
47
53
54
55
56
57
58
62
63
64
65
66
67
68
72
73
74
75
79
80
81
82
83
87
88
89
90
91
92
93
96
97
98
99
100
104
105
106
107
108
111
112
113
114
115
116
/* ... */
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "esp_err.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_littlefs.h"8 includes
static const char *TAG = "esp_littlefs";
void app_main(void)
{
ESP_LOGI(TAG, "Initializing LittleFS");
esp_vfs_littlefs_conf_t conf = {
.base_path = "/littlefs",
.partition_label = "storage",
.format_if_mount_failed = true,
.dont_mount = false,
}{...};
esp_err_t ret = esp_vfs_littlefs_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 LittleFS partition");
}{...} else {
ESP_LOGE(TAG, "Failed to initialize LittleFS (%s)", esp_err_to_name(ret));
}{...}
return;
}{...}
size_t total = 0, used = 0;
ret = esp_littlefs_info(conf.partition_label, &total, &used);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to get LittleFS partition information (%s)", esp_err_to_name(ret));
esp_littlefs_format(conf.partition_label);
}{...} else {
ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used);
}{...}
ESP_LOGI(TAG, "Opening file");
FILE *f = fopen("/littlefs/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("/littlefs/foo.txt", &st) == 0) {
unlink("/littlefs/foo.txt");
}{...}
ESP_LOGI(TAG, "Renaming file");
if (rename("/littlefs/hello.txt", "/littlefs/foo.txt") != 0) {
ESP_LOGE(TAG, "Rename failed");
return;
}{...}
ESP_LOGI(TAG, "Reading file");
f = fopen("/littlefs/foo.txt", "r");
if (f == NULL) {
ESP_LOGE(TAG, "Failed to open file for reading");
return;
}{...}
char line[128] = {0};
fgets(line, sizeof(line), f);
fclose(f);
char* pos = strpbrk(line, "\r\n");
if (pos) {
*pos = '\0';
}{...}
ESP_LOGI(TAG, "Read from file: '%s'", line);
ESP_LOGI(TAG, "Reading from flashed filesystem example.txt");
f = fopen("/littlefs/example.txt", "r");
if (f == NULL) {
ESP_LOGE(TAG, "Failed to open file for reading");
return;
}{...}
fgets(line, sizeof(line), f);
fclose(f);
pos = strpbrk(line, "\r\n");
if (pos) {
*pos = '\0';
}{...}
ESP_LOGI(TAG, "Read from file: '%s'", line);
esp_vfs_littlefs_unregister(conf.partition_label);
ESP_LOGI(TAG, "LittleFS unmounted");
}{ ... }