ESP32 Cam搭配SD卡:向函数传文件后读取失败问题
问题分析与解决
核心问题
printpassf函数接收了File参数但未使用,反而尝试打开不存在的/f.txt,这是读取失败的直接原因。- 调用
printpassf(file)前已执行file.close(),关闭后的文件对象无法再进行读取操作。
修正方案一:使用传入的文件对象
#include "SD_MMC.h" void printpassf(File &f){ if (!f || !f.available()) { Serial.println("File is unavailable or closed"); return; } Serial.println("File Content:"); while (f.available()) { Serial.write(f.read()); } f.close(); } void setup() { Serial.begin(115200); if (!SD_MMC.begin()) { Serial.println("Failed to mount card"); return; } // 以可写模式打开文件,写入后直接传递给函数读取 File file = SD_MMC.open("/test.txt", FILE_WRITE); if (!file) { Serial.println("Opening file to write failed"); return; } if (file.print("Test file write")) { Serial.println("File write success"); } else { Serial.println("File write failed"); } // 不提前关闭文件,传递给函数后处理关闭 printpassf(file); } void loop() {}
修正方案二:重新打开目标文件读取
#include "SD_MMC.h" void printpassf(){ File file2 = SD_MMC.open("/test.txt", FILE_READ); if (!file2) { Serial.println("Opening file to read failed"); return; } Serial.println("File Content:"); while (file2.available()) { Serial.write(file2.read()); } file2.close(); } void setup() { Serial.begin(115200); if (!SD_MMC.begin()) { Serial.println("Failed to mount card"); return; } File file = SD_MMC.open("/test.txt", FILE_WRITE); if (!file) { Serial.println("Opening file to write failed"); return; } if (file.print("Test file write")) { Serial.println("File write success"); } else { Serial.println("File write failed"); } file.close(); printpassf(); } void loop() {}
注意事项
- 传递
File对象时,必须保证对象处于未关闭状态,否则无法操作。 - 写入文件后,若选择重新打开读取,需确保
close()或flush()已执行,保证数据同步到SD卡。
内容的提问来源于stack exchange,提问作者lena
相关产品推荐
相关产品推荐

