File list SD card runs only 3 times

I use the slightly modified sample routine for the SD card to list the files in the directory.
After running 3 times the routine fails.
It seems there is a buffer full or something like that???

Data on serial port:

DATALOG.TXT		33609
TEST.TXT		288
DATALOG1.TXT		33609
DATALOG4.TXT		33609
DATALO~3.TXT		33609
TEST-K~1.TXT		288
DATALOG3.TXT		33609
DATALOG5.TXT		33609
DATALOG6.TXT		33609
DATALOG2.TXT		33609
done!
DATALOG.TXT		33609
TEST.TXT		288
DATALOG1.TXT		33609
DATALOG4.TXT		33609
DATALO~3.TXT		33609
TEST-K~1.TXT		288
DATALOG3.TXT		33609
DATALOG5.TXT		33609
DATALOG6.TXT		33609
DATALOG2.TXT		33609
done!
DATALOG.TXT		33609
TEST.TXT		288
DATALOG1.TXT		33609
DATALOG4.TXT		33609
DATALO~3.TXT		33609
TEST-K~1.TXT		288
DATALOG3.TXT		33609
DATALOG5.TXT		33609
done!
done!
done!
done!
#include <SD.h>

File root;

void setup()
{
  Serial.begin(9600);
  pinMode(5, OUTPUT);

  SD.begin(5);
  root = SD.open("/");


  
}

void loop()
{
  printDirectory(root, 0);
  Serial.println("done!");
  delay(5000);  
}

void printDirectory(File dir, int numTabs) {
   while(true) {

     File entry =  dir.openNextFile();
     if (! entry) {
       // no more files
       // return to the first file in the directory
       dir.rewindDirectory();
       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);
     } else {
       // files have sizes, directories do not
       Serial.print("\t\t");
       Serial.println(entry.size(), DEC);
     }
   }
}

You aren't closing any File objects...

fat16lib:
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." );
   
}