I'm trying to delete the oldest file from an sd card with SdFat with no success
I've found that function on Arduino forums Here
void deleteOldestFile(){
SdFile dirFile;
SdFile file;
SdFile oldestFile;
dir_t dir;
uint32_t oldestModified = 0xFFFFFFFF;
uint32_t lastModified;
if (!dirFile.open("/", O_READ)) {
sd.errorHalt("open root failed");
}
while (file.openNext(&dirFile, O_WRITE)) {
// Skip directories and hidden files.
if (!file.isSubDir() && !file.isHidden()) {
file.dirEntry(&dir);
lastModified = (uint16_t (dir.lastWriteDate) << 16 | dir.lastWriteTime);
if (lastModified < oldestModified ) {
oldestModified = lastModified;
oldestFile = file;
}
}
file.close();
}
if(!oldestFile.remove()) Serial.println("failed");
dirFile.close();
}
but I'm getting a "failed" message when this function run any idea why and how to fix this problem?
EDIT: I can use remove like that:
char delChar[13] = {0};
...
Serial.print("oldest: ");
oldestFile.printName();
oldestFile.getName(delChar,13);
Serial.println();
Serial.print("delchar: ");
Serial.println(delChar);
if(!sd.remove(delChar)) Serial.println("fail");
dirFile.close();
but the file.remove()
still not works
I see one bug in the code, that will cause problems finding the oldest file. It's not the main cause of the file.remove() problem, but it will cause trouble once you find and fix the file.remove() problem.
lastModified = (uint16_t (dir.lastWriteDate) << 16 | dir.lastWriteTime);
That uint16_t should be uint32_t instead. That error will cause the file's lastWriteDate to be treated as zero, because shifting an unsigned 16 bit number 16 bits to the left causes the result to be zero.
Here's a Sketch to illustrate the problem:
/*
* Simple Arduino Uno Sketch to show a bug and its corrected code.
*/
uint32_t oldestModified = 0xFFFFFFFF; // Tip: use 0xFFFFFFFFul to be unambiguous
uint16_t lastWriteDate = 5; // an arbitrary date
uint16_t lastWriteTime = 3; // an arbitrary time
void setup() {
uint32_t badLastModified;
uint32_t lastModified;
Serial.begin(9600);
delay(4000); // to give the user a chance to open the serial monitor.
Serial.print("oldestModified = 0x");
Serial.println(oldestModified, HEX);
badLastModified = (uint16_t (lastWriteDate) << 16 | lastWriteTime); // original
lastModified = (uint32_t (lastWriteDate) << 16 | lastWriteTime); // corrected
Serial.println();
Serial.print("badLastModified = 0x");
Serial.println(badLastModified, HEX);
Serial.print("lastModified = 0x");
Serial.println(lastModified, HEX);
}
void loop() {
}
Running this Sketch on an Arduino Uno produced this output:
oldestModified = 0xFFFFFFFF
badLastModified = 0x3
lastModified = 0x50003
User contributions licensed under CC BY-SA 3.0