Using the FileSystem to count files in a folder

I'm trying to create a function in my arduino sketch that will return the number of MP3 files that I've loaded onto the SD card of the yun, in the '/mnt/sda1/MP3' folder.

This is the code I have so far:

#include <Bridge.h>
#include <FileIO.h>

int _max = 0;

void setup() {
    Serial.begin(9600);
    FileSystem.begin();
    Bridge.begin();

    countMP3s();
    Serial.println(_max); 

}

void countMP3s() {
    _max = 0;
    File mp3s = FileSystem.open("/mnt/sda1/MP3");
    mp3s.rewindDirectory();
    while (true) {
        File f = mp3s.openNextFile();
        if (f) {
            if (String(f.name()).endsWith(".mp3") ) {
                _max++;
            }
            f.close();
        } else {
            break;
        }
    }
    mp3s.close();
}

The problem I'm running into is that my countMP3s() function only ever returns a value of '1' - even though there are multiple .mp3 files within the /mnt/sda1/MP3 folder. It looks like for some reason its breaking out of the while loop early, but I can't figure out why.

Can anyone help on this?

Another side question: Is it necessary to include the 'FileSystem.begin();' line for this? Is this required whenever using the File class in the arduino sketch? Just want to confirm

Thanks for any help!

find /etc -maxdepth 1 -type f | wc -l
32

at ETC directory has 32 files.

ATmega32u4 Code:

#include <Process.h>
void setup() {
  Bridge.begin();   // Initialize the Bridge
  Serial.begin(9600);   // Initialize the Serial
  while (!Serial);  // Wait until a Serial Monitor is connected.
  countfiles();
}
void loop() { }
void countfiles() {
  Process p;
  p.runShellCommand("find /etc -maxdepth 1 -type f | wc -l");
  while (p.running());
  while (p.available()) {
    int result = p.parseInt();          // look for an integer
    Serial.println(result);       // print the number as well
    break;
  }
}

change "/etc" to "/mnt/sda1/MP3"

Thanks! this does definitely work for counting files.

However, I'm still interested in knowing why my original approach wasn't working. Is there an explanation for that?

rhammell:
...
However, I'm still interested in knowing why my original approach wasn't working. Is there an explanation for that?

Even original approach worked , there are a lot of round trip API call, the code will run very slow if a lot of files at directory. Might not be worth the effect.