LittleFS/File System read failing

Hi,

Trying to get the File System working to write and read a file to the LittleFS onboard flash. According to the below code we are able to write a file that is correct size but are always getting garbage reading it out after a reset.
Can anyone spot what I’m doing wrong?

STARTUP(System.enableFeature(FEATURE_RETAINED_MEMORY));
STARTUP(System.enableFeature(FEATURE_RESET_INFO));
SYSTEM_THREAD(ENABLED);
SYSTEM_MODE(SEMI_AUTOMATIC);

#include <fcntl.h>

void setup() {
  pinMode(D22,OUTPUT);
  digitalWrite(D22,HIGH);
  Serial.begin();
  delay(5000);
  digitalWrite(D22,LOW);
  int _currentFD = open("settings.txt", O_RDWR | O_CREAT | O_TRUNC);

  struct stat sbuf;

  fstat(_currentFD,&sbuf);

  if (sbuf.st_size==0) {
    uint8_t buf[]={'h','e','l','l','o',' ','w','o','r','l','d'};
    write(_currentFD,buf,11);
    fsync(_currentFD);
    Serial.println("Writing");
  } else {
    Serial.printlnf("Reading fs {%d}",sbuf.st_size);
    uint8_t buf[11];
    read(_currentFD,buf,11);

    for (uint a=0;a<11;a++) {
      Serial.printf("[%02x]",buf[a]);
    }
    unlink("settings.txt");
  }
  Serial.println();
  Serial.println("Press any key to reset");
  while (!Serial.available()){};
  close(_currentFD);
  delay(100);

  System.reset();

}


void loop() {
}
[Connected]
Writing

Press any key to reset
[Disconnected]
[Connected]
Reading fs {11}
[78][5d][01][20][00][00][00][00][00][00][00]
Press any key to reset
[Disconnected]

You are truncating the file to 0 length every time it’s opened (both when writing and reading). And yes, fstat() will show that it’s not 0 length until it’s closed or synced to the filesystem with the above example. If you check file length with lseek() with the actual handle after opening, it will be 0.

 O_TRUNC
              If the file already exists and is a regular file and the
              access mode allows writing (i.e., is O_RDWR or O_WRONLY)
              it will be truncated to length 0.  If the file is a FIFO
              or terminal device file, the O_TRUNC flag is ignored.
              Otherwise, the effect of O_TRUNC is unspecified.

Arrrg. Yes. Thanks. Just needed a fresh set of eyes.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.