Go Down

Topic: ESP32: SD.open() erase file content (Read 447 times) previous topic - next topic

filu_to_ja

Hi,

Once SD.open(filename, FILE_WRITE) it erases whole file content. According to SD.h spec:
"FILE_WRITE: open the file for reading and writing, starting at the end of the file."
In my understanding, it should append new content to an existing one.

Has anyone faced this problem before? Is there someone who can help me?

Wiring: https://camo.githubusercontent.com/fe6b89251ae4df2628b1a4c86c57976f22d6d5ba/687474703a2f2f692e696d6775722e636f6d2f34436f584f75522e706e67

Code:
#include <SD.h>

String filename = "/new_file.txt";
File file;
void setup() {
  pinMode(5, OUTPUT);
  SD.begin(5);
 
  Serial.begin(115200);
  Serial.println("Setup Start");
 
  file = SD.open(filename, FILE_WRITE);
  file.println("First line");
  file.close();

  Serial.println("first print:");
  PrintFile();

  file = SD.open(filename, FILE_WRITE);
  file.println("Second Line");
  file.close();

  Serial.println("second print:");
  PrintFile();
}

void loop() {
  // put your main code here, to run repeatedly:

}

void PrintFile() {
      file = SD.open(filename, FILE_READ);
      String file_data = "";
      while(file.available()){
        file_data += (char)file.read();
      }
      Serial.println(file_data);
      file.close();
}

Serial Monitor output:
Setup Start
first print:
First line

second print:
Second Line

Juraj

some versions of SD library don't open the file for append if you use WRITE

filu_to_ja

I use standard lib from Arduino 1.8.10.
Which one should I use?

Juraj

ESP32 boards package has own version of SD and there FILE_WRITE is not FILE_APPEND. use FILE_APPEND     

filu_to_ja


Go Up