Problem with directory listings after other file IO

Hi all. I am using a Seeedstudio SD Shield on my Arduino, and using the SD library that ships with the current Arduino package, I'm seeing some issues.

First of all, the example code that prints out a directory does not close the files that it opens up.

Secondly, here's the main issue i'm seeing:

  1. get a directory listing (using the code from the included examples)
  2. create a file (or read a file) (using code from the included examples)
  3. get a directory listing again (same code as 1 above)

The second directory listing is missing a significant amount of files. The first time, i see 25 files, the second time, and all subsequent calls to get a directory listing, i see only 10 files.

I've tried this on multiple cards of varying speeds and sizes, and see the same results.

(This is ultimately for my TinyBasicPlus Arduino BASIC port, so i need to be able to get the directory listing multiple times, etc)

Attached is the .ino showing this issue. Any help or suggestions would be appreciated.

-s

listfiles_testing.ino (2.46 KB)

Anyone? Is the SD Library included just flawed? Should I start looking at alternatives? I haven't figured out why it's failing, but I have been able to reproduce it on multiple different pieces of hardware.

First of all, the example code that prints out a directory does not close the files that it opens up.

So, fix the example. It was never stated that it was perfect. It was provided to illustrate how to do something.

There is a bug in the SD library for opening root that causes the position of root to not be at the beginning.

Add a dir.seek(0) to your printDirectory function like this:

void printDirectory(File dir, int numTabs) 
{
  int nEntries = 0;
  char buf[32];
  dir.seek(0);
   while(true) {
     
     File entry =  dir.openNextFile();
     if (! entry) {
       // no more files
       //Serial.println("**nomorefiles**");
       entry.close(); // Added
       break;
     }
     for (uint8_t i=0; i<numTabs; i++) {
       Serial.print('\t');
     }
     Serial.print(entry.name());
     if (entry.isDirectory()) {
       //Serial.println("/");
       //printDirectory(entry, numTabs+1); // no recursion
     } else {
       // files have sizes, directories do not
       Serial.print("\t\t");
       Serial.println(entry.size(), DEC);
       nEntries++;
     }
     entry.close(); // Added
   }
   
   sprintf( buf, "%d", nEntries );
   
   Serial.println( "" );
   Serial.print( buf );
   Serial.println( " entries found." );
   
}

re: dir.seek(0) -- Thanks! That's exactly what I needed. It's working perfectly now! :smiley: :smiley:

PaulS: Yes. I did fix everything myself

Yes. I did fix everything myself

Good. Too many people come here thinking the examples must be perfect and are afraid to change them.

I'm glad that you were able to get the correct answer, and the results that you wanted.

1 Like