Skip to content

Commit a771214

Browse files
committed
BUGFIX - file read and seek edit
1 parent 7dc8ca4 commit a771214

File tree

1 file changed

+26
-8
lines changed

1 file changed

+26
-8
lines changed

Diff for: libraries/FS/src/vfs_api.cpp

+26-8
Original file line numberDiff line numberDiff line change
@@ -376,21 +376,33 @@ size_t VFSFileImpl::read(uint8_t* buf, size_t size)
376376
if(_isDirectory || !_f || !buf || !size) {
377377
return 0;
378378
}
379-
380-
//ERASE BYTEBUFFER and use read when size > READ_SIZE_SWITCH always
381-
if(size > READ_SIZE_SWITCH)
379+
380+
if(size > READ_SIZE_SWITCH) //to be tested -> switch between fread/read to optimize speeds (call sd status check only once for each read)
382381
{
383-
//check some data in buffer exists –> clear buffer and move pointer to deleted data
384382
size_t bytesinbuf = __fpending(_f);
385-
if (bytesinbuf && (bytesinbuf != 128)) //buffer lenght is 128 bytes
383+
size_t buf_size = __fbufsize(_f);
384+
385+
if (bytesinbuf && (bytesinbuf != buf_size)) //buffer size SD=128 , LittleFS=4096
386386
{
387+
fpos_t pointer = 0;
388+
//clear buffer
387389
fpurge(_f);
388-
lseek(fileno(_f),(-128+bytesinbuf),SEEK_CUR);
390+
//get file pointer
391+
fgetpos(_f, &pointer);
392+
393+
if(pointer <= buf_size){
394+
lseek(fileno(_f),(-pointer+bytesinbuf),SEEK_CUR);
395+
}
396+
else{
397+
uint64_t modulo = pointer % buf_size;
398+
lseek(fileno(_f),(-modulo+bytesinbuf),SEEK_CUR);
399+
}
389400
}
390401

391402
int res = ::read(fileno(_f), buf, size);
392403
if (res < 0) {
393404
// an error occurred
405+
log_d("FILE READ ERROR OCCURED");
394406
return 0;
395407
}
396408
return res;
@@ -416,8 +428,14 @@ bool VFSFileImpl::seek(uint32_t pos, SeekMode mode)
416428
if(_isDirectory || !_f) {
417429
return false;
418430
}
419-
auto rc = fseek(_f, pos, mode);
420-
return rc == 0;
431+
432+
off_t res = lseek(fileno(_f), pos, mode);
433+
if (res < 0) {
434+
// an error occurred
435+
log_d("FILE SEEK ERROR OCCURED");
436+
return 1; //return error -> for seek its all above 0
437+
}
438+
return 0; //return success -> for fseek its 0
421439
}
422440

423441
size_t VFSFileImpl::position() const

0 commit comments

Comments
 (0)