Page 1 of 1

Interacting with files

Posted: Thu Nov 25, 2021 10:36 pm
by br0kenpixel
I'm trying to add a function to the uos module which should create an empty file on my ESP32.
Something like this:

Code: Select all

STATIC mp_obj_t test() {
    mp_int_t ret_val;
    printf("attempting to create file \"test.txt\"\n");
    FILE* file;
    file = fopen("test.txt", "w");
    if(file == NULL){
        printf("file pointer is null\n");
        ret_val = 0;
    } else {
        printf("file pointer OK\n");
        fclose(file);
        ret_val = 1;
    }
    return mp_obj_new_int(ret_val);
}
MP_DEFINE_CONST_FUN_OBJ_0(test_obj, test);
However, if I run this, I just get "file pointer is null". I'm assuming that I cannot use standard C functions to interact with the filesystem. I probably have to use some other "special" functions, however I could not find any documentation on this.
Does anyone know what functions I have to use to do this? It also would be nice if I could do other operations, like writing data to a file, reading it, delete it, etc.

Re: Interacting with files

Posted: Fri Nov 26, 2021 12:35 am
by russ_h
I've been using Dave Hylands mpfile.c and mpfile.h code.

Re: Interacting with files

Posted: Fri Nov 26, 2021 2:11 am
by dhylands
For stuff like deleting and renaming files, you can take a look at the mp_vfs_xxx functions which are found here:
https://github.com/micropython/micropyt ... h#L93-L103

The functions for performing reads/writes are found here:
https://github.com/micropython/micropyt ... #L243-L256
and they point to mp_stream_xxx_obj which is a python objext, and the C function is declared STATIC:
https://github.com/micropython/micropyt ... #L275-L301

This means that the C functions aren't exposed, so what mpfile.c/.h does is to look up the python functions and call them.

The wrapper functions (like mp_readinto) take C style arguments and convert them to python style arguments and then call the python function.

Currently, mpfile.c only implements mp_readinto, but you could easily add functions for others found in vfs_posix_file.c

The arguments for most of the functions will be the same as for CPython, but I generally look at the C source to figure out what the arguments are.