@@ -18,6 +18,15 @@ typedef struct _mp_obj_fdfile_t {
18
18
int fd ;
19
19
} mp_obj_fdfile_t ;
20
20
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
+
21
30
STATIC const mp_obj_type_t rawfile_type ;
22
31
23
32
STATIC 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
27
36
28
37
STATIC machine_int_t fdfile_read (mp_obj_t o_in , void * buf , machine_uint_t size , int * errcode ) {
29
38
mp_obj_fdfile_t * o = o_in ;
39
+ check_fd_is_open (o );
30
40
machine_int_t r = read (o -> fd , buf , size );
31
41
if (r == -1 ) {
32
42
* errcode = errno ;
@@ -36,6 +46,7 @@ STATIC machine_int_t fdfile_read(mp_obj_t o_in, void *buf, machine_uint_t size,
36
46
37
47
STATIC machine_int_t fdfile_write (mp_obj_t o_in , const void * buf , machine_uint_t size , int * errcode ) {
38
48
mp_obj_fdfile_t * o = o_in ;
49
+ check_fd_is_open (o );
39
50
machine_int_t r = write (o -> fd , buf , size );
40
51
if (r == -1 ) {
41
52
* errcode = errno ;
@@ -46,6 +57,9 @@ STATIC machine_int_t fdfile_write(mp_obj_t o_in, const void *buf, machine_uint_t
46
57
STATIC mp_obj_t fdfile_close (mp_obj_t self_in ) {
47
58
mp_obj_fdfile_t * self = self_in ;
48
59
close (self -> fd );
60
+ #ifdef MICROPY_CPYTHON_COMPAT
61
+ self -> fd = -1 ;
62
+ #endif
49
63
return mp_const_none ;
50
64
}
51
65
STATIC 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
57
71
58
72
STATIC mp_obj_t fdfile_fileno (mp_obj_t self_in ) {
59
73
mp_obj_fdfile_t * self = self_in ;
74
+ check_fd_is_open (self );
60
75
return MP_OBJ_NEW_SMALL_INT ((machine_int_t )self -> fd );
61
76
}
62
77
STATIC MP_DEFINE_CONST_FUN_OBJ_1 (fdfile_fileno_obj , fdfile_fileno );
0 commit comments