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()); }
5 comments on Reading the directory on an SD card:
Please log in to post comments.
Jim, how do I get the file and SDcard information, date modified, file size, free memory etc. Something like MSDOS chkdsk.
Paul