MAJOR LAUNCH: HUSKYLENS 2 6 TOPS LLM MCP AI Vision Sensor is now available. Buy Now →
#include "FS.h"Moving on to the Arduino setup, we will start by opening a serial connection. Then we will mount the file system, since we always need to do it before we start interacting with it.
Serial.begin(115200);
Serial.println();
if(!SPIFFS.begin()){
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}
After that, we will create a file called “test.txt”, to make sure we have a file to which we can later append content. You can check in detail how to write a file on this previous post.File fileToWrite = SPIFFS.open("/test.txt", "w");
if(!fileToWrite){
Serial.println("There was an error opening the file for writing");
return;
}
if(fileToWrite.println("ORIGINAL FILE LINE")){
Serial.println("File was written");
} else {
Serial.println("File write failed");
}
File fileToAppend = SPIFFS.open("/test.txt", "a");
if(!fileToAppend){
Serial.println("There was an error opening the file for appending");
return;
}
if(fileToAppend.println("APPENDED FILE LINE")){
Serial.println("File content was appended");
} else {
Serial.println("File append failed");
}
Then we will close the file with a call to the close method on our File object.fileToAppend.close();
File fileToRead = SPIFFS.open("/test.txt", "r");
if(!fileToRead){
Serial.println("Failed to open file for reading");
return;
}
Serial.println("File Content:");
while(fileToRead.available()){
Serial.write(fileToRead.read());
}
fileToRead.close();
The final complete code can be seen below.#include "FS.h"
void setup() {
Serial.begin(115200);
Serial.println();
if(!SPIFFS.begin()){
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}
//--------- Write to file ---------------
File fileToWrite = SPIFFS.open("/test.txt", "w");
if(!fileToWrite){
Serial.println("There was an error opening the file for writing");
return;
}
if(fileToWrite.println("ORIGINAL FILE LINE")){
Serial.println("File was written");
} else {
Serial.println("File write failed");
}
fileToWrite.close();
//--------- Apend to file --------------
File fileToAppend = SPIFFS.open("/test.txt", "a");
if(!fileToAppend){
Serial.println("There was an error opening the file for appending");
return;
}
if(fileToAppend.println("APPENDED FILE LINE")){
Serial.println("File content was appended");
} else {
Serial.println("File append failed");
}
fileToAppend.close();
//---------- Read from file --------------
File fileToRead = SPIFFS.open("/test.txt", "r");
if(!fileToRead){
Serial.println("Failed to open file for reading");
return;
}
Serial.println("File Content:");
while(fileToRead.available()){
Serial.write(fileToRead.read());
}
fileToRead.close();
}
void loop() {}