Open agdl opened 8 years ago
From @RobTillaart on January 19, 2013 19:29
Discussed on the forum here - https://forum.arduino.cc/t/sd-exists-has-weird-side-effect/139821
From @gertrude on January 20, 2013 14:44
...where the practical answer is, SD.exists() monkeys about with internal state such that subsequent openNextFile() calls fail, unless the caller also remembers to judiciously call rewindDirectory().
I suggest this violates the Principal of Least Surprise: SD.exists() should tidy up after itself, so it doesn't cause later failures in other functions. The results of openNextFile() ideally shouldn't depend on the context within which it was called.
Has this ever been fixed? I've just run into this same problem. The only difference is that it doesn't matter if I place root = SD.open("/");
before or after my SD.exists()
routine, it fails either way.
Hmm, what I've noticed is that if I hard-code the filename, all is fine, but if I try to pass in a variable, it freaks out. So:
This works:
SD.exists("/data");
But this doesn't:
const char* DATA_DIR = "/data";
SD.exists(DATA_DIR);
And neither does this:
#define DATA_DIR "/data"
SD.exists(DATA_DIR);
Try this fix: https://github.com/arduino/Arduino/pull/3647
@PaulStoffregen I checked the link, but I cannot see how that problem applies here. Thanks for the quick response, though!
Weirdly enough, it's the const
qualifier it cannot stomach. Despite the fact that the compiler has no problem with it. Really weird.
Anyway, this will work just fine:
char* DATA_DIR = "/data"; // NOT const char* !
SD.exists(DATA_DIR);
But will, of course, give you a warning: deprecated conversion from string constant to char*
From @blowback on January 17, 2013 13:20
If I take the listfiles.ino example and change the chip select to 4, I can get a directory listing of the contents of my SD card, as expected.
If I modify the code by adding SD.exists("foo);' immediately before the 'root = SD.open("/");' then printDirectory() no longer works - specifically, the first call to dir.openNextFile() fails.
If I move the SD.exists() line to after the SD.open("/") line, then it works again.
I tried wrapping the SD.exists() with its own SD.open().....root.close(), but that caused the directory listing to fail again.
It doesn't matter if the file tested for actually exists or not, the behaviour is the same in both cases (and SD.exists() returns the right result).
Here's the code:
Copied from original issue: arduino/Arduino#1232