Reading the directory on an SD card

Here is a short code example that shows how to read the filenames from a directory on an SD card using the mbed SD filesystem. A sample code snippet (i.e., not a complete standalone program) is provided below that reads the filenames from this directory into a C++ vector of strings and prints all of the filenames out to the PC terminal application window. There is an existing C++ structure setup, "dirent", along with some functions such as "opendir" and "readdir" that can be used to read the directory entries that makes the code relatively short. This code assumes that the SD card file system is already setup in the program. "c_str()" is a handy function that converts a C++ string to a C style string (ends with a 0). For filenames longer than 8.3 characters, additional steps may be needed depending on the application and file system driver. This same approach will also work on mbed's local file system or a USB flash drive.

 #include "SDFileSystem.h"
 #include <string>
 #include <vector>

//.....assumes SDFileSystem is setup in earlier code for device "/sd"

vector<string> filenames; //filenames are stored in a vector string
 
void read_file_names(char *dir)
{
    DIR *dp;
    struct dirent *dirp;
    dp = opendir(dir);
  //read all directory and file names in current directory into filename vector
    while((dirp = readdir(dp)) != NULL) {
        filenames.push_back(string(dirp->d_name));
    }
    closedir(dp);
}

//....example call in your "main" code somewhere.....

 // read file names into vector of strings
 read_file_names("/sd/myDir");
 // print filename strings from vector using an iterator
 for(vector<string>::iterator it=filenames.begin(); it < filenames.end(); it++)  
  {
    printf("%s\n\r",(*it).c_str());
  }


Report

4 comments on Reading the directory on an SD card:

25 Mar 2014

Jim, how do I get the file and SDcard information, date modified, file size, free memory etc. Something like MSDOS chkdsk.

Paul

26 Mar 2014

There is a stat function, but have not tried it on mbed's filesystem.

http://stackoverflow.com/questions/14612355/finding-file-size-with-c has some example code

22 Oct 2014

I'm having trouble using the "readdir()" function. I am able to open a directory successfully using "opendir()," but my program crashes once it gets to readdir(dp). I tried printing out the return value, which I thought might be NULL, but I found that the function never actually finishes executing, so nothing is returned. Is anyone else having this issue?

08 May 2015

Hi!! What about how to read a file on the flash memory?

Thank you!!

Please log in to post comments.