SunFounder ESP32 Starter Kit
File file = SD_MMC.open("/test.txt", FILE_WRITE);
if (!file) {
Serial.println("Failed to open file for writing"); // Print error␣
˓→message if file failed to open
return;
}
• Write data to the file
Write the text “Test file write” to the file. If the write operation is successful, it prints “File write
successful”; otherwise, it prints “File write failed”.
if(file.print("Test file write")) { // Write the message to the file
Serial.println("File write success"); // If write succeeds, print to␣
˓→serial
} else {
Serial.println("File write failed"); // If write fails, print to serial
}
• Close the file
Close the opened file. This ensures that any buffered data is written to the file and the file is properly
closed.
file.close(); // Close the file
• Open the root directory
Open the root directory of the SD card. If the directory fails to open, it prints “Failed to open directory”
and returns.
File root = SD_MMC.open("/"); // Open the root directory of SD card
if (!root) {
Serial.println("Failed to open directory"); // Print error message if␣
˓→directory failed to open
return;
}
• Print each file’s name and size
The loop starting with while (File file = root.openNextFile()) iterates over all the files in
the root directory, printing each file’s name and size to the serial monitor.
Serial.println("Files found in root directory:"); // Print the list of␣
˓→files found in the root directory
while (File file = root.openNextFile()) { // Loop through all the files in␣
˓→the root directory
Serial.print(" ");
Serial.print(file.name()); // Print the filename
Serial.print("\t");
Serial.println(file.size()); // Print the filesize
file.close(); // Close the file
}
3. This loop() function is an empty loop and does nothing in the current program. However, in a typical Arduino
program, this function would continuously loop over and execute the code within it. In this case, since all the
154 Chapter 1. For Arduino User