Table of Contents

LittleFS (Little File System) is a lightweight file system designed for microcontrollers and embedded systems. It is an alternative to SPIFFS (SPI Flash File System) and is often used with ESP32 for storing small files like configuration data, logs, or web assets.

LittleFS vs SPIFFS

FeatureLittleFSSPIFFS
Wear leveling✅ Yes✅ Yes
Power-loss safety✅ Better❌ Worse
Performance✅ Faster⚠️ Slower
Directory support✅ Yes❌ No
Reliability✅ More stable⚠️ Less stable

Since SPIFFS is deprecated, LittleFS is the recommended file system for ESP32.

Why Use LittleFS on ESP32?

  1. Power Loss Resilience – Designed to handle unexpected power failures better than SPIFFS.
  2. Wear Leveling – Reduces flash memory wear, extending its lifespan.
  3. Better Performance – Faster file operations compared to SPIFFS.
  4. Supports Directories – Unlike SPIFFS, LittleFS allows directory structures.

Example: Using LittleFS on ESP32

This example demonstrates how to initialize LittleFS, write to a file, read from it, and delete a file.

Since Arduino ESP32 Core v2, LittleFS is built-in, we no longer need to install a separate library.

Include Required Headers & Initialize LittleFS

#include "FS.h"
#include "LittleFS.h"  // No need for external library

#define FORMAT_LITTLEFS_IF_FAILED true

void setup() {
    Serial.begin(115200);

    // Mount LittleFS
    if (!LittleFS.begin(FORMAT_LITTLEFS_IF_FAILED)) {
        Serial.println("LittleFS Mount Failed");
        return;
    }
    Serial.println("LittleFS Mounted Successfully");

    // Write data to a file
    writeFile("/test.txt", "Hello, LittleFS!");

    // Read data from the file
    readFile("/test.txt");

    // Delete file
    deleteFile("/test.txt");
}

void loop() {
}

** Function to Write Data to a File**

void writeFile(const char *path, const char *message) {
    Serial.printf("Writing to file: %s\n", path);
    File file = LittleFS.open(path, "w");
    if (!file) {
        Serial.println("Failed to open file for writing");
        return;
    }
    file.print(message);
    file.close();
    Serial.println("Write successful");
}

Function to Read Data from a File

void readFile(const char *path) {
    Serial.printf("Reading file: %s\n", path);
    File file = LittleFS.open(path, "r");
    if (!file) {
        Serial.println("Failed to open file for reading");
        return;
    }
    while (file.available()) {
        Serial.write(file.read());
    }
    file.close();
    Serial.println("\nRead complete");
}

Function to Delete a File

void deleteFile(const char *path) {
    Serial.printf("Deleting file: %s\n", path);
    if (LittleFS.remove(path)) {
        Serial.println("File deleted successfully");
    } else {
        Serial.println("Failed to delete file");
    }
}

Categorized in:

Storage,

Tagged in: