Skip to content

Seek mode "SeekEnd" attempts to read outside of file #11

@Aircoookie

Description

@Aircoookie

First off all, thank you so much @lorol for making the best embedded FS easily usable on ESP32! It's highly appreciated :)

I've ran into a problem with the seek() function, specifically in SeekEnd mode. It doesn't set the position correctly and attempting to read just causes 255 to be read. On closer inspection it seems like SeekEnd takes the file end and adds the offset to it (instead of subtracting), thus setting the position outsite the file. I would have tried setting a negative offset, but the seek() function only takes an unsigned integer.

Should it matter, this is with CONFIG_LITTLEFS_FOR_IDF_3_2 defined to enable support for the current ESP32 core release 1.0.4.

MCVE

#include <Arduino.h>
#include "LITTLEFS.h"

void printChar(char r) {
  Serial.print(r);
  Serial.print(" (");
  Serial.print((byte)r);
  Serial.println(")");
}

void setup() {
  Serial.begin(112500);
  delay(2000);

  LITTLEFS.begin(true);
  File f = LITTLEFS.open("/test.txt", "w");
  f.print("test1234");
  f.close();
  Serial.println("Wrote file.");

  f = LITTLEFS.open("/test.txt", "r");
  uint32_t fsize = f.size();

  //this is very inefficient, for demo purposes only
  Serial.println("Reading with SeekSet");
  Serial.print("File size ");
  Serial.println(f.size());
  for (int i = 0; i < fsize; i++) {
    f.seek(i,SeekSet);
    Serial.print("pos ");
    Serial.print(f.position());
    Serial.print(" --> ");
    
    printChar(f.read());
  }

  Serial.println("Reading with SeekEnd");
  for (int i = 1; i < fsize + 1; i++) {
    f.seek(i,SeekEnd);
    Serial.print("pos ");
    Serial.print(f.position());
    Serial.print(" --> ");

    printChar(f.read());
  }

}

void loop() {

}

Output

Wrote file.
Reading with SeekSet
File size 8
pos 0 --> t (116)
pos 1 --> e (101)
pos 2 --> s (115)
pos 3 --> t (116)
pos 4 --> 1 (49)
pos 5 --> 2 (50)
pos 6 --> 3 (51)
pos 7 --> 4 (52)
Reading with SeekEnd
pos 9 --> � (255)
pos 10 --> � (255)
pos 11 --> � (255)
pos 12 --> � (255)
pos 13 --> � (255)
pos 14 --> � (255)
pos 15 --> � (255)
pos 16 --> � (255)

For reference, the correct output from the ESP8266 version of LittleFS

Wrote file.
Reading with SeekSet
File size 8
pos 0 --> t (116)
pos 1 --> e (101)   
pos 2 --> s (115)   
pos 3 --> t (116)   
pos 4 --> 1 (49)    
pos 5 --> 2 (50)
pos 6 --> 3 (51)
pos 7 --> 4 (52)
Reading with SeekEnd
pos 7 --> 4 (52)
pos 6 --> 3 (51)
pos 5 --> 2 (50)
pos 4 --> 1 (49)
pos 3 --> t (116)
pos 2 --> s (115)
pos 1 --> e (101)
pos 0 --> t (116)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions