What Is Needed To Use fopen() On An Embedded System?

c, embedded, file, fopen

Solution

Check the documentation for your toolchain's C library - it should have something to say about re-targeting the library.

For example if you are using Newlib you must re-implement some or all of the [syscalls stubs][3] to suit your target. The low level `open()` syscall in this case will allow `fopen()` to work as necessary. At its simplest, you might implement `open()` to support higher-level stdio access to serial ports, but if you are expecting standard file-system access, then you will still need an underlying file-system to map it too.

Another example of re-targeting the Keil/ARM standard library can be found here.

Problem

I am quite new to the FILE family of functions that the standard C library provides. I recently stumbled across `fopen()` and the similar functions after researching how `stdout`, `stdin` and `stderr` work alongside functions like `printf()`. I was wondering, what is needed to use `fopen()` on an embedded system (which doesn't necessarily have operating system support). After reading more about it, is seems like a cool thing to do on more powerful embedded systems to hook into say, a UART/SPI interface, so that calling `printf()` would print data out of the UART. Simarly, you could read data from a UART buffer by calling `scanf()`. This would also increase portability! (code written for say, Linux, would be easier to port if `printf()` was supported). You could also print debug data to a file if it was running in a production environment, and read from it later. Can you just use `fopen()` on a bare-bones embedded system? If so who/where/when is the "FILE" then created (as far as I now, `fopen()` does not `malloc()` space for the file, nor do you specify how much)? Or do you need a operating system with FAT file support. If so, would something like http://ultra-embedded.com/?fat_filelib work? Would using FreeRTOS help at all?

Original source