@@ -18,6 +18,15 @@ typedef struct _mp_obj_fdfile_t {
1818 int fd ;
1919} mp_obj_fdfile_t ;
2020
21+ #ifdef MICROPY_CPYTHON_COMPAT
22+ void check_fd_is_open (const mp_obj_fdfile_t * o ) {
23+ if (o -> fd < 0 )
24+ nlr_raise (mp_obj_new_exception_msg (& mp_type_ValueError , "I/O operation on closed file" ));
25+ }
26+ #else
27+ #define check_fd_is_open (o )
28+ #endif
29+
2130STATIC const mp_obj_type_t rawfile_type ;
2231
2332STATIC void fdfile_print (void (* print )(void * env , const char * fmt , ...), void * env , mp_obj_t self_in , mp_print_kind_t kind ) {
@@ -27,6 +36,7 @@ STATIC void fdfile_print(void (*print)(void *env, const char *fmt, ...), void *e
2736
2837STATIC machine_int_t fdfile_read (mp_obj_t o_in , void * buf , machine_uint_t size , int * errcode ) {
2938 mp_obj_fdfile_t * o = o_in ;
39+ check_fd_is_open (o );
3040 machine_int_t r = read (o -> fd , buf , size );
3141 if (r == -1 ) {
3242 * errcode = errno ;
@@ -36,6 +46,7 @@ STATIC machine_int_t fdfile_read(mp_obj_t o_in, void *buf, machine_uint_t size,
3646
3747STATIC machine_int_t fdfile_write (mp_obj_t o_in , const void * buf , machine_uint_t size , int * errcode ) {
3848 mp_obj_fdfile_t * o = o_in ;
49+ check_fd_is_open (o );
3950 machine_int_t r = write (o -> fd , buf , size );
4051 if (r == -1 ) {
4152 * errcode = errno ;
@@ -46,6 +57,9 @@ STATIC machine_int_t fdfile_write(mp_obj_t o_in, const void *buf, machine_uint_t
4657STATIC mp_obj_t fdfile_close (mp_obj_t self_in ) {
4758 mp_obj_fdfile_t * self = self_in ;
4859 close (self -> fd );
60+ #ifdef MICROPY_CPYTHON_COMPAT
61+ self -> fd = -1 ;
62+ #endif
4963 return mp_const_none ;
5064}
5165STATIC MP_DEFINE_CONST_FUN_OBJ_1 (fdfile_close_obj , fdfile_close );
@@ -57,6 +71,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(fdfile___exit___obj, 4, 4, fdfile___e
5771
5872STATIC mp_obj_t fdfile_fileno (mp_obj_t self_in ) {
5973 mp_obj_fdfile_t * self = self_in ;
74+ check_fd_is_open (self );
6075 return MP_OBJ_NEW_SMALL_INT ((machine_int_t )self -> fd );
6176}
6277STATIC MP_DEFINE_CONST_FUN_OBJ_1 (fdfile_fileno_obj , fdfile_fileno );
0 commit comments