'Arduino SD -> File extension

I found this example to list all files on the SD Card:

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

 File entry =  dir.openNextFile();
 if (! entry) {
   // no more files
   //Serial.println("**nomorefiles**");
   break;
 }
 for (uint8_t i=0; i<numTabs; i++) {
   Serial.print('\t');
 }
 if (entry.type
 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);
 }

} }

But I want to list only the files with an explicit extension and save them into an array. Any one of you an Idea? I can't found any Function to get the file extension by the SD Class.



Solution 1:[1]

Unfortunately you will need to loop through each of the filenames individually.

please look at an example of my code that does just this. Similar to the above comment by "A Person".

Here are links to my actual use WHERE I use it and THE filter function

Note that my above use is using the SdFatLib, a more advanced version that SD (the IDE provided) library. Below I have adapted the same function for SD. Should work as it merely inspects the pointed char arrary's last 4 characters.

FYI - Note that the SD and SdFatLib only support 8.3 format.

void printDirectory(File dir, int numTabs) {
  while(true) {
    File entry =  dir.openNextFile();
    if (! entry) {
      // no more files
      break;
    }
    for (uint8_t i=0; i<numTabs; i++) {
      Serial.print('\t');
    }

    if ( isFnMusic(entry.name()) ) { // Here is the magic
      Serial.print(entry.name());
    }

    if (entry.isDirectory()) { // Dir's will print regardless, you may want to exclude these
      Serial.print(entry.name());
      Serial.println("/");
      printDirectory(entry, numTabs+1);
    } else {
      // files have sizes, directories do not
      Serial.print("\t\t");
      Serial.println(entry.size(), DEC);
    }
    entry.close();
  }
}

bool isFnMusic(char* filename) {
  int8_t len = strlen(filename);
  bool result;
  if (  strstr(strlwr(filename + (len - 4)), ".mp3")
     || strstr(strlwr(filename + (len - 4)), ".aac")
     || strstr(strlwr(filename + (len - 4)), ".wma")
     || strstr(strlwr(filename + (len - 4)), ".wav")
     || strstr(strlwr(filename + (len - 4)), ".fla")
     || strstr(strlwr(filename + (len - 4)), ".mid")
     // and anything else you want
    ) {
    result = true;
  } else {
    result = false;
  }
  return result;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mpflaga