SdFat not reading in the loop

I have basically the following code (very paraphrased, most guards removed for ease. Real code attached).
Using greiman’s SdFat here: GitHub - greiman/SdFat: Arduino FAT16/FAT32 exFAT Library

#include <SdFat.h>

SdFat sd;
SdFile file;

void setup() 
{
  sd.begin(chipSelect, spiSpeed);
    int MaxFiles = 0;
    while (file.openNext(sd.vwd(), O_READ)) {
      MaxFiles++;
      file.close();
    }
    cout << "Init: " << MaxFiles << endl;
}

void loop() 
{
  int MaxFiles = 0;
  while (file.openNext(sd.vwd(), O_READ)) {
    MaxFiles++;
    file.close();
  }
  cout << "Loop: " << MaxFiles << endl;
}

I basically get this output:
Init: 83
Loop: 0

It seems that the openNext is failing in the loop.

Anyone have any ideas?

inttest.ino (2.65 KB)

I figured it out.

If isOpen() then it fails to openNext()

You need to close() it first. :/

(or just create a macro to close it if open before opening the next.)

The real problem with the example you posted is that sd.vwd() is at the end of the root directory in loop. You positioned it in setup().

You need to rewind sd.vwd() in loop like this:

void loop() 
{
  sd.vwd()->rewind();  // <<----- Add this
  int MaxFiles = 0;  
  while (file.openNext(sd.vwd(), O_READ)) {
    MaxFiles++;
    file.close();
  }
  cout << "Loop: " << MaxFiles << endl;
  while(1);
}

In general you must position a directory to the start if you want to use openNext() to traverse the entire directory.