@@ -33,6 +33,12 @@ STATIC mp_uint_t file_obj_read(mp_obj_t self_in, void *buf, mp_uint_t size, int
3333
3434 pyb_file_obj_t * self = MP_OBJ_TO_PTR (self_in );
3535
36+ if (self -> opened == false) {
37+ // Return EINVAL just as FatFS if the file is not opened
38+ * errcode = MP_EINVAL ;
39+ return MP_STREAM_ERROR ;
40+ }
41+
3642 xSemaphoreTake (self -> littlefs -> mutex , portMAX_DELAY );
3743 lfs_ssize_t sz_out = lfs_file_read (& self -> littlefs -> lfs ,& self -> fp , buf , size );
3844 xSemaphoreGive (self -> littlefs -> mutex );
@@ -48,6 +54,12 @@ STATIC mp_uint_t file_obj_write(mp_obj_t self_in, const void *buf, mp_uint_t siz
4854
4955 pyb_file_obj_t * self = MP_OBJ_TO_PTR (self_in );
5056
57+ if (self -> opened == false) {
58+ // Return EINVAL just as FatFS if the file is not opened
59+ * errcode = MP_EINVAL ;
60+ return MP_STREAM_ERROR ;
61+ }
62+
5163 xSemaphoreTake (self -> littlefs -> mutex , portMAX_DELAY );
5264 lfs_ssize_t sz_out = lfs_file_write (& self -> littlefs -> lfs , & self -> fp , buf , size );
5365 // Request timestamp update if file has been written successfully
@@ -91,6 +103,12 @@ STATIC mp_uint_t file_obj_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg,
91103
92104 } else if (request == MP_STREAM_FLUSH ) {
93105
106+ if (self -> opened == false) {
107+ // Return EINVAL just as FatFS if the file is not opened
108+ * errcode = MP_EINVAL ;
109+ return MP_STREAM_ERROR ;
110+ }
111+
94112 xSemaphoreTake (self -> littlefs -> mutex , portMAX_DELAY );
95113 int res = lfs_file_sync (& self -> littlefs -> lfs , & self -> fp );
96114 xSemaphoreGive (self -> littlefs -> mutex );
@@ -102,8 +120,9 @@ STATIC mp_uint_t file_obj_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg,
102120 return 0 ;
103121
104122 } else if (request == MP_STREAM_CLOSE ) {
105- // This check is needed here because calling close() twice makes LFS crash in lfs_file_close()
123+
106124 if (self -> opened == false) {
125+ // Return 0 just as FatFs if the file is not opened
107126 return 0 ;
108127 }
109128
@@ -115,6 +134,7 @@ STATIC mp_uint_t file_obj_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg,
115134 * errcode = littleFsErrorToErrno (res );
116135 return MP_STREAM_ERROR ;
117136 }
137+
118138 self -> opened = false; // indicate a closed file
119139 return 0 ;
120140 } else {
0 commit comments