You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 23:22:54