Skip to content

Commit 019d54f

Browse files
committed
Raise ValueError when reading/writing a file that is closed.
To be compatible with CPython's behaviour.
1 parent d231463 commit 019d54f

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

source/microbit/filesystem.c

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,12 @@ mp_obj_t microbit_remove(mp_obj_t filename) {
326326
return mp_const_none;
327327
}
328328

329+
static void check_file_open(file_descriptor_obj *self) {
330+
if (!self->open) {
331+
nlr_raise(mp_obj_new_exception_msg(&mp_type_ValueError, "I/O operation on closed file"));
332+
}
333+
}
334+
329335
static int advance(file_descriptor_obj *self, uint32_t n, bool write) {
330336
DEBUG(("FILE DEBUG: Advancing from chunk %d, offset %d.\r\n", self->seek_chunk, self->seek_offset));
331337
self->seek_offset += n;
@@ -350,7 +356,8 @@ static int advance(file_descriptor_obj *self, uint32_t n, bool write) {
350356

351357
mp_uint_t microbit_file_read(mp_obj_t obj, void *buf, mp_uint_t size, int *errcode) {
352358
file_descriptor_obj *self = (file_descriptor_obj *)obj;
353-
if (!self->open || self->writable || file_system_chunks[self->start_chunk].marker == FREED_CHUNK) {
359+
check_file_open(self);
360+
if (self->writable || file_system_chunks[self->start_chunk].marker == FREED_CHUNK) {
354361
*errcode = EBADF;
355362
return MP_STREAM_ERROR;
356363
}
@@ -379,7 +386,8 @@ mp_uint_t microbit_file_read(mp_obj_t obj, void *buf, mp_uint_t size, int *errco
379386

380387
mp_uint_t microbit_file_write(mp_obj_t obj, const void *buf, mp_uint_t size, int *errcode) {
381388
file_descriptor_obj *self = (file_descriptor_obj *)obj;
382-
if (!self->open || !self->writable || file_system_chunks[self->start_chunk].marker == FREED_CHUNK) {
389+
check_file_open(self);
390+
if (!self->writable || file_system_chunks[self->start_chunk].marker == FREED_CHUNK) {
383391
*errcode = EBADF;
384392
return MP_STREAM_ERROR;
385393
}

0 commit comments

Comments
 (0)