Skip to content

Commit 8ee67ab

Browse files
Return FALSE on seek past EOF (#7324)
Fixes #7323 While I'm not a fan, the Arduino FileSeek API online shows that a seek() past EOF should return FALSE. https://www.arduino.cc/en/Reference/FileSeek SPIFFS and SDFS obey this, but LittleFS followed the POSIX standard or allowing seeks past EOF. Update LittleFS::seek() to follow the Arduino API and add tests for it.
1 parent 27ef03f commit 8ee67ab

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

libraries/LittleFS/src/LittleFS.h

+5
Original file line numberDiff line numberDiff line change
@@ -377,11 +377,16 @@ class LittleFSFileImpl : public FileImpl
377377
if (mode == SeekEnd) {
378378
offset = -offset; // TODO - this seems like its plain wrong vs. POSIX
379379
}
380+
auto lastPos = position();
380381
int rc = lfs_file_seek(_fs->getFS(), _getFD(), offset, (int)mode); // NB. SeekMode === LFS_SEEK_TYPES
381382
if (rc < 0) {
382383
DEBUGV("lfs_file_seek rc=%d\n", rc);
383384
return false;
384385
}
386+
if (position() > size()) {
387+
seek(lastPos, SeekSet); // Pretend the seek() never happened
388+
return false;
389+
}
385390
return true;
386391
}
387392

tests/host/fs/test_fs.inc

+24
Original file line numberDiff line numberDiff line change
@@ -174,6 +174,30 @@ TEST_CASE(TESTPRE "open(w+) truncates file", TESTPAT)
174174
REQUIRE( t == "");
175175
}
176176

177+
TEST_CASE(TESTPRE "peek() returns -1 on EOF", TESTPAT)
178+
{
179+
FS_MOCK_DECLARE(64, 8, 512, "");
180+
REQUIRE(FSTYPE.begin());
181+
createFile("/file1", "some text");
182+
auto f = FSTYPE.open("/file1", "r+");
183+
REQUIRE(f.seek(8));
184+
REQUIRE(f.peek() == 't');
185+
REQUIRE(f.read() == 't');
186+
REQUIRE(f.peek() == -1);
187+
REQUIRE(f.read() == -1);
188+
f.close();
189+
}
190+
191+
TEST_CASE(TESTPRE "seek() pase EOF returns error (#7323)", TESTPAT)
192+
{
193+
FS_MOCK_DECLARE(64, 8, 512, "");
194+
REQUIRE(FSTYPE.begin());
195+
createFile("/file1", "some text");
196+
auto f = FSTYPE.open("/file1", "r+");
197+
REQUIRE_FALSE(f.seek(10));
198+
f.close();
199+
}
200+
177201
#ifdef FS_HAS_DIRS
178202

179203
#if FSTYPE != SDFS

0 commit comments

Comments
 (0)