The Serial Peripheral Interface Flash File System, or SPIFFS, is a lightweight filesystem for the ESP32 built on top of SPI NOR Flash devices. SPIFFS is designed to store files on flash memory in an efficient and uniform way. In ESP32, SPIFFS helps you do more advanced operations, giving you access to files to read from and write to, creating directories and other file manipulating functions.
This guide will touch on opening a file, listing a directory, creating a file, writing to a file, reading a file and removing a file using the SPIFFS filesystem. Most importantly, it outlines when not to use this filesystem.
#include "FS.h"
#include "SPIFFS.h"
void setup() {
Serial.begin(115200);
if(!SPIFFS.begin(true)) { // Initialize SPIFFS
Serial.println("An error has occurred while mounting SPIFFS");
return;
}
else {
Serial.println("SPIFFS mounted successfully");
}
}
File file = SPIFFS.open("/sample.txt", FILE_WRITE);
if(!file) {
Serial.println("There was an error opening the file for writing");
return;
}
file.close();
File file = SPIFFS.open("/sample.txt");
if(!file || file.isDirectory()) {
Serial.println("Failed to open file for reading");
return;
}
File file = SPIFFS.open("/sample.txt", FILE_WRITE);
if(!file) {
Serial.println("Failed to open file for writing");
return;
}
int bytesWritten = file.println("Hello World"); // Returns the number of bytes written
if(bytesWritten <= 0) {
Serial.println("Write failed or file was not open");
}
File file = SPIFFS.open("/sample.txt");
if(!file || file.isDirectory()) {
Serial.println("Failed to open file for reading");
return;
}
while(file.available()) {
Serial.write(file.read());
}
file.close();
File root = SPIFFS.open("/");
File file = root.openNextFile();
while(file) {
Serial.print("FILE: ");
Serial.println(file.name());
file = root.openNextFile();
}
if(SPIFFS.remove("/sample.txt")) {
Serial.println("File removed");
} else {
Serial.println("Remove failed");
}
SPIFFS is great for storing large data objects, like configuration files or web pages for ESP32 servers. However, SPIFFS does not support directories - all files live in the same namespace. Also, SPIFFS does not support modifying or appending to a file beyond the current end of the file, unlike typical desktop OS filesystems.
SPIFFS, due to the nature of flash memory and the need to minimize writes, keeps track of file writes and deletes in a very non-intuitive way. As such, it's not always able to recover all of the previous space from deleted files. It's also worth noting that SPIFFS has a limited lifetime, much like any flash memory.
If you need to store small amounts of variable data, such as configuration information, consider using the built-in Preferences Library in the ESP32 Core instead.
Sources: