SD card - deleting the oldest file

Bodger62

Member
Hello Everyone,

I am trying to read a list of files from my SD card and delete the oldest. For some reason
the file name that is stored to be deleted is the last one read from the list instead of the oldest.

I am converting the time that the file was modified into unix time to find the oldest file and
this seems to work okay.

I have attached the results that I get when I run the program and a list of files that are stored
on the SD card.

I look forward to any help that you can give me.

regards,
Ray
 

Attachments

  • Delete_SD_Files.ino
    6.2 KB · Views: 25
  • Results.txt
    1.1 KB · Views: 20
  • Files_on_SD_card.odt.txt
    127.1 KB · Views: 26
Code:
        if (file_unix_time < last_file_unix_time)
        {
          last_file_unix_time = file_unix_time;
          file_to_delete = entry.name();
          Serial.printf("\r\nFile name %s  %s\r\n", entry.name(), file_to_delete);
        }
I think that file_to_delete is saving a pointer to a string within the 'entry' object. It is not the string itself. Each time around the loop the content of the entry.name() string is changed to the current file which is why it ends up always being the last file name in the list.
You need to make your own copy of the string instead of using a pointer.

Pete
 
Hello Pete,

I changed the code as shown below

if (unix_start_time < last_file_unix_time)
{
last_file_unix_time = unix_start_time;
strcpy(&file_to_delete[0], entry.name());
save_file_count = file_count;
}

having changed file_to_delete from a pointer to char file_to_delete[16] and everything is now working as expected.

Thanks for your help,

regards,

Ray
 
It might be wise to increase the size of the array unless you are sure you'll only ever have 8.3 formatted filenames.

Pete
 
And ideally use strncpy() to avoid the risk of overflow no matter what filenames get thrown at you.
Code:
const int filename_max_len = 32;
char file_to_delete[filename_max_len+1];
file_to_delete[filename_max_len]=0; // ensure we always have a null terminator
...
if (unix_start_time < last_file_unix_time)
{
last_file_unix_time = unix_start_time;
strncpy(file_to_delete, entry.name(), filename_max_len);
save_file_count = file_count;
}
 
Back
Top