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!

AlexSp3
  • 203
  • 1
  • 8

2 Answers2

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

AlexSp3
  • 203
  • 1
  • 8
0

I had the same problem with a nano esp32. I used the esp32 SD.h. The FILE_WRITE is a macro for "w", FILE_READ a macro for "r". By specifying mode as "w+r", SD.open(fname,"w+r"); I was able to randomly access the file.