How to read a file using C language
How to read a file using C language
I'm currently using MicroPython to develop esp32 board. Now I need to read a file in flash in main.c. How could I do this? Could anybody show me an example? Thanks
Re: How to read a file using C language
You can use mp_vfs_open (see extmod/vfs.h) to open the file which will return a stream object, that you can use mp_stream_rw (or mp_stream_read_exactly) to read bytes from (see py/stream.h). You can see an example of this vfs_reader.c (which is what is used by the lexer to load Python files from flash).
This is how builtin "open" works (see esp32/mpconfigport.h where it maps mp_builtin_open to mp_vfs_open).
Re: How to read a file using C language
Thanks Jimmo, Your advice is quite helpful.jimmo wrote: ↑Wed Nov 11, 2020 12:12 amYou can use mp_vfs_open (see extmod/vfs.h) to open the file which will return a stream object, that you can use mp_stream_rw (or mp_stream_read_exactly) to read bytes from (see py/stream.h). You can see an example of this vfs_reader.c (which is what is used by the lexer to load Python files from flash).
This is how builtin "open" works (see esp32/mpconfigport.h where it maps mp_builtin_open to mp_vfs_open).
What if I want to modify the file from flash with C? Which file could be useful for me?
Re: How to read a file using C language
Exactly the same -- mp_stream_rw
Re: How to read a file using C language
Hi Jimmo, I've got another problem. When I call mp_reader_new_file function, it works well. But if I directly call mp_vfs_open, the "NLR jump failed error" occurs. Could you please help me figure out what might cause this problem? Thanks.
Re: How to read a file using C language
NLR is the way exceptions are handled in MicroPython -- this means that mp_vfs_open is raising an exception which your code is not handling. Here's an example of writing an exception handler in C:
Code: Select all
nlr_buf_t nlr;
if (nlr_push(&nlr) == 0) {
// do stuff
nlr_pop();
} else {
mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val));
return MP_OBJ_NULL;
}
Re: How to read a file using C language
Thanks, helped me as well.jimmo wrote: ↑Wed Nov 11, 2020 12:12 amYou can use mp_vfs_open (see extmod/vfs.h) to open the file which will return a stream object, that you can use mp_stream_rw (or mp_stream_read_exactly) to read bytes from (see py/stream.h). You can see an example of this vfs_reader.c (which is what is used by the lexer to load Python files from flash).
This is how builtin "open" works (see esp32/mpconfigport.h where it maps mp_builtin_open to mp_vfs_open).