Is there documentation for the directory function? I remember it exists but can never find it in the documentation. I’d think it would be on the SD card page but maybe its elsewhere?
Showing the files on an SD card
johnsondavies
#22
Yes, I seem to have forgotten that. I’ve added it to the Language reference page and the SD card interface page, and thanks for pointing it out!
hasn0life
#23
I modified the directory function to let you enter an optional path so you can look into folders. In this version it returns a cons pair with the file name and size if its a file and just the name if its a directory but that can be commented out if one wants only filenames.
//change the entry code to 0201 so denote the function can accept one argument
object *fn_directory(object *args, object *env) {
(void) env;
char *sd_path_buf = NULL;
SDBegin();
File root;
object *result = cons(NULL, NULL);
object *ptr = result;
if (args != NULL) {
object *arg1 = checkstring(first(args));
int len = stringlength(arg1) + 2; //make it longer for the initial slash and the null terminator
sd_path_buf = (char*)malloc(len);
if(sd_path_buf != NULL){
cstring(arg1, &sd_path_buf[1], len-1);
sd_path_buf[0] = '/'; //really weird way to concatenate a slash to the front...
root = SD.open(sd_path_buf);
} //what if malloc fails? :0
}
else{
root = SD.open("/");
}
while (true) {
File entry = root.openNextFile();
if (!entry) break; // no more files
object *filename = lispstring((char*)entry.name());
if (entry.isDirectory()) {
cdr(ptr) = cons(filename, NULL);
}else{
cdr(ptr) = cons(cons(filename, number(entry.size())), NULL);
}
ptr = cdr(ptr);
entry.close();
}
if(sd_path_buf != NULL) free(sd_path_buf);
root.close();
return cdr(result);
}
Here’s how it works in practice:
17288> (directory)
(("Greeting.txt" . 18) ("name.txt" . 28) ("name2.txt" . 18) ("tedt1.CL" . 13) "System Volume Information" "example folder")
17902> (directory "example folder")
(("stuff.txt" . 59))
17902> (directory "System Volume Information")
(("IndexerVolumeGuid" . 76) ("WPSettings.dat" . 12))
17902> (directory (nth 5 (directory)))
(("stuff.txt" . 59))
17902> (caar (directory (nth 5 (directory))))
"stuff.txt"