Delete only first four files

I have an issue with this code from topic.

#include "SPIFFS.h"

char* filelist[12];
int i;

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

 if (!SPIFFS.begin(true))
 {
 Serial.println("An Error has occurred while mounting SPIFFS");
 return;
 }

 File root = SPIFFS.open("/");

 File file = root.openNextFile();

 while(file)
 {

 if(strncmp(file.name(), "/LOG", 4) == 0)
 {     
   
 i++;
 filelist[i] = strdup(file.name());
 Serial.print(filelist[i]);
 Serial.print("  ");
 Serial.print(i);
 Serial.println("");
 
 }

 file = root.openNextFile();
 }

 for(i = 1;i < 5; i++)  //Delete only first four files; keep from getting too many log files.
 {
 
 SPIFFS.remove(filelist[i]);
 Serial.print("Removed:  ");
 Serial.print(filelist[i]);
 Serial.print("  ");
 Serial.print(i);
 Serial.println("");

 }

 i = 0;
 
}

void loop() {}

Filenames have the naming convention of "LOG + DATE + MONTH +YEAR + .TXT" Actual filename for example "LOG1905.TXT." Issue occurs when files are out of sequence by DATE.

Is there a way to start indexing from the begining of the root directory each time files are put into array? File system is SPIFFS.

Files.JPG

I am trying to delete only files LOG05052020.TXT, LOG16052020.TXT, LOG17052020.TXT, LOG18052020.TXT.

William

Files.JPG

You are getting the files from the "beginning of the root directory" - That's your problem. You are too used to file systems (such as Windows) which sort them for you, before displaying them. Most file systems don't store them in any particular order. They just use a free slot in the directory, typically the next available one, or the first previously deleted entry.

If you can, adjust your naming convention to LOGYYYYMMDD.TXT Then a standard lexicological sort of all the names (which I suspect you will have to do yourself) will yield them in ascending date order.

Edit: Alternatively, if you don't have storage for all of the filenames in order to sort them: 1. Write a function to search for, and delete, the oldest file. This only requires storage for 2 filenames. 2. Call the function 4 times.