ESP8266 SPIFFS example

In this example we will look at SPIFFS , SPIFFS, or spiffs (Serial Peripheral Interface Flash File System) is a method for creating a file system in NOR-type flash memory

File system object (SPIFFS)

begin

SPIFFS.begin()

This method mounts SPIFFS file system. It must be called before any other FS APIs are used. Returns true if file system was mounted successfully, false otherwise.

format

SPIFFS.format()

Formats the file system. May be called either before or after calling begin. Returns true if formatting was successful.

open

SPIFFS.open(path, mode)

Opens a file. path should be an absolute path starting with a slash (e.g. /dir/filename.txt). mode is a string specifying access mode. It can be one of “r”, “w”, “a”, “r+”, “w+”, “a+”. Meaning of these modes is the same as for fopen C function.

Returns File object. To check whether the file was opened successfully, use the boolean operator.

File f = SPIFFS.open("/f.txt", "w");
if (!f) {
    Serial.println("file open failed");
}

exists

SPIFFS.exists(path)

Returns true if a file with given path exists, false otherwise.

openDir

SPIFFS.openDir(path)

Opens a directory given its absolute path. Returns a Dir object.

remove

SPIFFS.remove(path)

Deletes the file given its absolute path. Returns true if file was deleted successfully.

rename

SPIFFS.rename(pathFrom, pathTo)

Renames file from pathFrom to pathTo. Paths must be absolute. Returns true if file was renamed successfully.

info

FSInfo fs_info;
SPIFFS.info(fs_info);

Fills FSInfo structure with information about the file system. Returns true is successful, false otherwise.

Filesystem information structure

 

struct FSInfo {
    size_t totalBytes;
    size_t usedBytes;
    size_t blockSize;
    size_t pageSize;
    size_t maxOpenFiles;
    size_t maxPathLength;
};

This is the structure which may be filled using FS::info method. Field names are self-explanatory.

Directory object (Dir)

 

The purpose of Dir object is to iterate over files inside a directory. It provides three methods: next()fileName(), and openFile(mode).

The following example shows how it should be used:

Dir dir = SPIFFS.openDir("/data");
while (dir.next()) {
    Serial.print(dir.fileName());
    File f = dir.openFile("r");
    Serial.println(f.size());
}

dir.next() returns true while there are files in the directory to iterate over. It must be called before calling fileName and openFile functions.

openFile method takes mode argument which has the same meaning as for SPIFFS.open function.

File object

 

SPIFFS.open and dir.openFile functions return a File object. This object supports all the functions of Stream, so you can use readBytesfindUntil,parseIntprintln, and all other Stream methods.

There are also some functions which are specific to File object.

seek

file.seek(offset, mode)

This function behaves like fseek C function. Depending on the value of mode, it moves current position in a file as follows:

  • if mode is SeekSet, position is set to offset bytes from the beginning.
  • if mode is SeekCur, current position is moved by offset bytes.
  • if mode is SeekEnd, position is set to offset bytes from the end of the file.

Returns true if position was set successfully.

position

file.position()

Returns the current position inside the file, in bytes.

size

file.size()

Returns file size, in bytes.

name

String name = file.name();

Returns file name, as const char*. Convert it to String for storage.

close

file.close()

Close the file. No other operations should be performed on File object after closefunction was called.

 

Code Example

[codesyntax lang=”cpp”]

#include "FS.h"

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

  // always use this to "mount" the filesystem
  bool result = SPIFFS.begin();
  Serial.println("SPIFFS opened: " + result);

  // this opens the file "myfile.txt" in read-mode
  File testFile = SPIFFS.open("/myfile.txt", "r");
  
  if (!testFile) 
  {
    Serial.println("File doesn't exist yet. Creating it");

    // open the file in write mode
    File testFile = SPIFFS.open("/myfile.txt", "w");
    if (!testFile) 
    {
      Serial.println("file creation failed");
    }
    //write two lines
    testFile.println("this is line 1");
    testFile.println("this is line 2");
  } 
  else 
  {
    // we could open the file
    while(testFile.available()) 
    {
      //read line by line from the file
      String line = testFile.readStringUntil('\n');
      Serial.println(line);
    }

  }
  testFile.close();
}

void loop() 
{
}

[/codesyntax]

 

Output

Open the serial monitor

SPIFFS opened:
File doesn’t exist yet. Creating it

Now reset the board

SPIFFS opened:
this is line 1
this is line 2

 

Related posts

Creating an infrared thermometer with a Wemos Mini and a MLX90614

ESP8266 based TMP175 temperature display project

ESP8266 MPL3115A2 pressure sensor project