1.创建分区
2.挂载SPIFFS文件系统
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
};
// Use settings defined above to initialize and mount SPIFFS filesystem.
// Note: esp_vfs_spiffs_register is an all-in-one convenience function.
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;
}
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);
}
// Check consistency of reported partiton size info.
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);
// Could be also used to mend broken files, to clean unreferenced pages, etc.
// More info at https://github.com/pellepl/spiffs/wiki/FAQ#powerlosses-contd-when-should-i-run-spiffs_check
if (ret != ESP_OK) {
ESP_LOGE(TAG, "SPIFFS_check() failed (%s)", esp_err_to_name(ret));
return;
} else {
ESP_LOGI(TAG, "SPIFFS_check() successful");
}
}
这里就不给注释了,详细请移步到乐鑫官网
3.创建文件,这里使用C语言标准库去创建fopen
//创建一个文件
FILE *f;
f = fopen(file, "w");
if(f == NULL)
{
printf("创建文静失败\n");
}
//创建成功后关闭文件
fclose(f);
ESP_LOGI(TAG, "创建文件成功");
4.将用户自定义数据写入文件系统55
void file_write(void)
{
typedef struct
{
int a;
int b;
int c;
}DATA;
DATA data = {0};//这里使用结构体去写数据
data.a = 11;
data.b = 12;
data.c = 13;
printf("write data >>>>>>>>>>>\n");
printf("%d\n", data.a);
printf("%d\n", data.b);
printf("%d\n", data.c);
printf(">>>>>>>>>>>>>>>>>>>>>>\n");\
//将以上数据写入文件系统
FILE *f;
f = fopen(file,"w");
if(f == NULL)
{
printf("write file is error\n");
}
fwrite(&data, sizeof(data), 1, f);
fclose(f);
ESP_LOGI(TAG, "保存成功");
}
5.读取用户写入文件系统数据,并打印出来
//读取用户的数据
void SPIFFS_readfile(void)
{
FILE *f;
f = fopen(file, "r");
if(f == NULL)
{
printf("open file is error\n");
}
fread(&data,sizeof(data),1,f);
printf("%d\n", data.a);
printf("%d\n", data.b);
printf("%d\n", data.c);
fclose(f);
ESP_LOGI(TAG, "读取成功");
}
6.成功运行