memfile.h – Reading files from memory with fscanf

Often times it is extremely convenient to compile certain assets, or data, straight into C code. This can be nice when creating code for someone else to use. For example in the tigr graphics library by Richard Mitton various shaders and font files are directly included as character arrays into the C source. Another example is in dear imgui where some font files (and probably other things) are embedded straight into the source.

The reason this is useful is embedding things in source removes dependencies from code. The less dependencies the better. The easier it is for someone to grab your code and solve problems, the better your code is.

I’ve created a single header called memfile.h that implements a function for opening a file in memory, and also implements a bunch of fscanf overloads. Here is a link to the github repository.

Here’s the readme:

memfile is a C header for opening files in memory by mimicking the functionaliy of fopen and fscanf. memfile is not compatible with standard C FILE pointers, but works pretty much the same way. Here’s a quick example:

Just include memfile.h and you’re good to go. I’ve created an example to demonstrate usage in main.c. As extra goodies I’ve included the incbin script I used to generate the poem symbol from main.c (incbin.pl stolen from Richard Mitton).

Here’s example usage:

 

TwitterRedditFacebookShare

4 thoughts on “memfile.h – Reading files from memory with fscanf

  1. emingh

    Hi, mmap (the memory mapping) already exists to this purpose. How is your code different than the mmap?

    Reply
    1. Randy Gaul Post author

      Well mmap certainly invokes sys calls of some kind. If an array is embedded into the program directly no sys calls are necessary to interface with data. Also the code I wrote should be portable to any platform. Lastly a nice thing about embedding data directly into source code is it reduces dependencies, e.g. nobody needs to download source code as well as make sure appropriate assets are in the correct place. Downsides to embedding things directly into source code is the linker has to chew through the data, and there is a limit to how much memory can be loaded into the process space at program start (iirc I was dealing with a 2GB limit on Windows recently, but I’m not sure about other platforms).

      Reply
    1. Randy Gaul Post author

      Never tried it but it looks perfect! Too bad it doesn’t seem to exist on Windows :(

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *