SD.exists() has weird side effect

If I take the SD example “listfiles.ino” and run it on my Uno+Wireless SD shield, it lists the files on the SD card. So far so good.

If I add a single SD.exists call at the start, like this:

 if(SD.exists("META.DAT"))    // <----- ADDED THIS
        Serial.println("DOESN'T EXIST");
    root ="/");
        Serial.println("root opened");
        printDirectory(root, 0);

then the directory listing now returns nothing at all. The still succeeds, but the call to dir.openNextFile() inside printDirectory() always fails.

It doesn’t matter if the file I’m testing for actually exists on the SD card or not - SD.exists() returns the right result, but in either case dir.openNextFile() will fail.

This looks like I bug, unless I’m misusing it in some way…

And did you dive into the code what could cause it?

had a quick look at the SD lib (in your arduino path) and the exists function calls the walkpath(...) function to walk the tree to see if it exists. What I saw it traverses the whole directory so some pointers might be at the end.

can you try rewindDirectory() ?

Which version of the Arduino are you using BTW?"/") doesn't really open root. It just gives you a pointer to the already open internal root object.

The root file is positioned by SD.exists(). printDirectory() does not position dir so its behavior depends on the current position of dir.

Try calling rewindDirectory() before calling printDirectory() like this:

  printDirectory(root, 0);

It's a Uno, with a wireless SD shield. Yes, rewindDir() fixes it, thanks all.

@fat16lib Thank you for noting to call rewindDirectory (I was having many issues with this) before using printDirectory.

I was trying to pass-through a modified library function that passes back file creation time, so I could convert it to a unix-time with timezone offset for comparing values. So I would call printDirectory to get a list of fileNames, then check creation date time. When I tried:

** if (!entryFile.dirEntry(&d)) {** ** Serial.println("Error Date");** ** }**

it would shift the position printDirectory started at and causes the first one to fail. Using the rewindDirectory before printDirectory fixed it though.