-->
Page 1 of 5

SPIFFS file read and write example

PostPosted: Mon Feb 15, 2016 6:03 pm
by gerardwr
Today I coded a basic sketch getting to learn to use the SPIFFS filesystem.

The sketch is attached here, maybe it's of use to anyone.

Code: Select all// Very basic Spiffs example, writing 10 strings to SPIFFS filesystem, and then read them back
// For SPIFFS doc see : https://github.com/esp8266/Arduino/blob/master/doc/filesystem.md
// Compiled in Arduino 1.6.7. Runs OK on Wemos D1 ESP8266 board.

#include "FS.h"

void setup() {
  Serial.begin(9600);
  Serial.println("\nVery basic Spiffs example, writing 10 lines to SPIFFS filesystem, and then read them back");
  SPIFFS.begin();
  // Next lines have to be done ONLY ONCE!!!!!When SPIFFS is formatted ONCE you can comment these lines out!!
  Serial.println("Please wait 30 secs for SPIFFS to be formatted");
  SPIFFS.format();
  Serial.println("Spiffs formatted");
}

void loop() {

  // open file for writing
  File f = SPIFFS.open("/f.txt", "w");
  if (!f) {
      Serial.println("file open failed");
  }
  Serial.println("====== Writing to SPIFFS file =========");
  // write 10 strings to file
  for (int i=1; i<=10; i++){
    f.print("Millis() : ");
    f.println(millis());
    Serial.println(millis());
  }

  f.close();

  // open file for reading
  f = SPIFFS.open("/f.txt", "r");
  if (!f) {
      Serial.println("file open failed");
  }  Serial.println("====== Reading from SPIFFS file =======");
  // write 10 strings to file
  for (int i=1; i<=10; i++){
    String s=f.readStringUntil('\n');
    Serial.print(i);
    Serial.print(":");
    Serial.println(s);
  }

  // wait a few seconds before doing it all over again
  delay(3000);
 
}

Re: SPIFFS file read and write example

PostPosted: Tue Feb 16, 2016 4:58 pm
by gerardwr
Just found a nice blog entry on the use of SPIFFS, including another basic example:
http://blog.squix.ch/2015/08/esp8266ard ... -with.html

Check it out!

Re: SPIFFS file read and write example

PostPosted: Fri Feb 26, 2016 5:17 am
by biol75
Is it possible to determine if the SPIFFS is already formatted, as I'd like to be able to write code like this;

if (???)
{
if (SPIFFS.format())
{...
}
else
{

Re: SPIFFS file read and write example

PostPosted: Sat Apr 02, 2016 4:24 pm
by gerardwr
biol75 wrote:Is it possible to determine if the SPIFFS is already formatted, as I'd like to be able to write code like this;
{


From the linked example above:
Code: Select all// this opens the file "f.txt" in read-mode
  File f = SPIFFS.open("/f.txt", "r");
   
  if (!f) {
    Serial.println("File doesn't exist yet. Creating it");