4

I'm trying to use a SD card with my ESP32 in order to save some variables in a txt file. Each variable uses 1 byte, so they can be represented by an 8 bit extended ASCII character.

The issue is it seems that the SD.h library has only 3 open modes (Read only, FILE_WRITE, FILE_APPEND), and I cannot figure out how to use random access for writing a specific byte of the file.

Imagine the situation: I have a file called myFile.txt which initially has a size of 5 bytes, and its content is: abcde

The code I'm using is the following:

#include <SPI.h>
#include <SD.h>

#define SD_CS_PIN 5

File myFile;

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(115200);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }


  Serial.println("Initializing SD card...");

  if (!SD.begin(SD_CS_PIN)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");



  myFile = SD.open("/myFile.txt", FILE_WRITE);
  myFile.seek(3);
  myFile.write('a');
  myFile.close();

}

void loop() {}

But after running the code, the file has an unexpected behaviour, its size changes from 5 bytes to 4 bytes, and its content is: abca instead of the expected abcae

I know it happens because when writing into the file I'm using the open mode FILE_WRITE which uses the FILE_APPEND mode internally, so when doing myFile.seek(3);, I'm truncating the file to 4 bytes since the FILE_APPEND mode needs to point to the end of the file.

So, my question is, how can I open a file in random access mode with SD.h, or another library?

Thanks in advance!

2
  • 1
    I would try to seek() to the end before close(). note: the SD library in ESP32 boards support package is different than the standard Arduino SD library.
    – Juraj
    Dec 14, 2021 at 13:43
  • @Juraj I tried it out but I got the same result, the first myFile.seek(3); truncates the file before.
    – AlexSp3
    Dec 14, 2021 at 14:00

1 Answer 1

3

Solved!

The solution was to migrate from the SD library to mySD, which seems to be a SdFat wrapper for ESP32.

You can see in the file mySD.h that the FILE_WRITE mode is defined as:

#define FILE_WRITE (F_READ | F_WRITE | F_CREAT)

Which means that it allows random access to the file for writing (F_WRITE instead of FILE_APPEND).

PS: I want to remark @Juraj comment since the forum is mainly for Arduino board questions

the SD library in ESP32 boards support package is different than the standard Arduino SD library

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.