Interacting with files

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
Post Reply
br0kenpixel
Posts: 5
Joined: Sun Dec 06, 2020 3:15 pm

Interacting with files

Post by br0kenpixel » Thu Nov 25, 2021 10:36 pm

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.

User avatar
russ_h
Posts: 88
Joined: Thu Oct 03, 2019 2:26 am
Contact:

Re: Interacting with files

Post by russ_h » Fri Nov 26, 2021 12:35 am

I've been using Dave Hylands mpfile.c and mpfile.h code.

User avatar
dhylands
Posts: 3821
Joined: Mon Jan 06, 2014 6:08 pm
Location: Peachland, BC, Canada
Contact:

Re: Interacting with files

Post by dhylands » Fri Nov 26, 2021 2:11 am

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.

Post Reply