documentation of file.rewindDirectory() is ambiguous and confusing #11734
Open
Description
opened on Dec 29, 2021
documentation https://www.arduino.cc/en/Reference/FileRewindDirectory of file.rewindDirectory() is ambiguous and confusing:
it actually make not undoubtedly clear for what ist's worth:
original example sketch:
#include <SD.h>
File root;
void setup()
{
Serial.begin(9600);
pinMode(10, OUTPUT);
SD.begin(10);
root = SD.open("/");
printDirectory(root, 0);
Serial.println("done!");
}
void loop()
{
// nothing happens after setup finishes.
}
void printDirectory(File dir, int numTabs) {
while(true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
// return to the first file in the directory
dir.rewindDirectory();
break;
}
for (uint8_t i=0; i<numTabs; i++) {
Serial.print('\t');
}
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);
}
}
}
OTOH, I can do fine WITHOUT .rewindDirectory() and if I use it and put it in though, it all messes up my directory file listing, multiple filenames are read and listed repeatedly:
String filelist[128];
// edit, meanwhile I use std::vector<String> filelist instead + push()
File SdPath;
volatile int filecount = 0;
//=================================================================
int readDirectory(File dir, int dirLevel) {
while (true) {
File entry = dir.openNextFile();
if (! entry) {
// no more files
// dir.rewindDirectory(); // don't do it! <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
break;
}
if(filecount==0) { // <<<<<< NEW
filelist[0]="/";
filecount++;
}
//Serial.print(entry.name());
filelist[filecount] = (String)entry.name();
if (entry.isDirectory()) {
//Serial.println("/");
filelist[filecount] += (String)"/";
//Serial.println(filelist[filecount]);
filecount++;
// <<< no more "/.."
readDirectory(entry, dirLevel + 1);
} else {
// files have sizes, directories do not
//Serial.println(filelist[filecount]);
//Serial.print("\t\t");
//Serial.println(entry.size(), DEC);
filecount++;
}
entry.close();
}
return filecount;
}
Activity