#include <FS.h>
Serial.begin(115200); Serial.println();After this we will mount the SPIFFS file system. This procedure always needs to be executed before we start to interact with the file system.
if (!success) { Serial.println("Error mounting the file system"); return; }Then we will write a file in the file system, to make sure we have some content to read. The procedure on how to write a file was covered in detail on this previous article.
File file = SPIFFS.open("/file.txt", "w"); if (!file) { Serial.println("Error opening file for writing"); return; } int bytesWritten = file.print("TEST SPIFFS"); if (bytesWritten == 0) { Serial.println("File write failed"); return; } file.close();
File file2 = SPIFFS.open("/file.txt", "r"); if (!file2) { Serial.println("Failed to open file for reading"); return; }
while (file2.available()) { Serial.write(file2.read()); }
file2.close();The final source code can be seen below.
#include <FS.h> void setup() { Serial.begin(115200); Serial.println(); bool success = SPIFFS.begin(); if (!success) { Serial.println("Error mounting the file system"); return; } File file = SPIFFS.open("/file.txt", "w"); if (!file) { Serial.println("Error opening file for writing"); return; } int bytesWritten = file.print("TEST SPIFFS"); if (bytesWritten == 0) { Serial.println("File write failed"); return; } file.close(); File file2 = SPIFFS.open("/file.txt", "r"); if (!file2) { Serial.println("Failed to open file for reading"); return; } Serial.println("File Content:"); while (file2.available()) { Serial.write(file2.read()); } file2.close(); } void loop() {}