You should close files as suggested by SurferTim to avoid memory leaks.
You must position the root directory by calling seek() before calling printDirectory(). SD.h returns a pointer to an internal file object for root and does not reposition root to the beginning.
The best mod is to add the seek call to printDirectory();
#include <SPI.h>
#include <SD.h>
File myFile;
void setup()
{
Serial.begin(9600);
pinMode(10, OUTPUT);
if (!SD.begin()) {
return;
}
myFile = SD.open("/");
printDirectory(myFile, 0);
myFile.close(); //// Add close /////////////
myFile = SD.open("test.txt", FILE_WRITE);
if (myFile) {
myFile.println("testing 1, 2, 3.");
myFile.close();
} else {
}
myFile = SD.open("/");
printDirectory(myFile, 0);
myFile.close(); ////// Add close /////
}
void loop() {
}
void printDirectory(File dir, int numTabs) {
dir.seek(0); /////// Add seek ///////////////////
while(true) {
File entry = dir.openNextFile();
if (! entry) {
break;
}
for (uint8_t i=0; i<numTabs; i++) {
Serial.print('\t');
}
Serial.print(entry.name());
Serial.print("\t\t");
Serial.println(entry.size(), DEC);
entry.close();
}
}