SD.remove(filename) is not working on Teensy 4.1

dlab

Active member
I have written a function that indicates the start of sending files on an SD card by printing the characters "analogData" and then each file in the SD card has its filename printed and then the data the file contains.
This function is supposed to delete the file after sending it over the Serial port, but it is not doing so.

Here is the code of the function:

Code:
void sendData() {
  File root = SD.open("/");
  Serial.println("analogData");
  int startTime = millis();
  File entry;

  while (File entry = root.openNextFile()) {
    Serial.print("filename: ");
    Serial.println(entry.name());

    while (entry.available()) {
      Serial.write(entry.read());
      delayMicroseconds(10);
    }

    Serial.println("fileDone");
    entry.close();
    SD.remove(String(entry.name()).c_str());  // this is the line that's not working
  }

  Serial.println("dataDone");
  root.close();
  Serial.print("I,Data transfer time taken in millis: ");
  Serial.println(millis() - startTime);
}

Everything works except for the SD.remove(String(entry.name()).c_str()); line.
What could be the problem here?
 
Try:
Code:
SD.remove( entry.name() );  // this is the line that's not working
The names are stored as Null terminated 'c' string ... not as a String.
 
Thank you for responding, the problem was quite silly :p
I was closing the file and then calling SD.remove(). All I had to do was move the SD.remove() line above the entry.close() line.
 
You could also just copy the filename to your own buffer or String before closing the directory entry. Then SD.remove() should be able to work even after you've closed the directory.
 
Minor note: Your current delete code or the variation as mentioned by PaulStoffregen will only work, with the file being deleted from the root directory of the SD.

Otherwise you need to construct the full logical path name for the file to be deleted.
 
Back
Top