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:
MEM_FILE fp; OpenFileInMemory( &fp, some_memory ); char buffer[ 256 ]; fscanf( &fp, "%s", buffer );
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:
#include <stdio.h> #include "memfile.h" // generated by incbin.pl from poem.txt const unsigned char poem[] = { 0x74,0x68,0x65,0x20,0x73,0x70,0x69,0x64,0x65,0x72,0x0d,0x0a,0x63,0x72,0x61,0x77, 0x6c,0x65,0x64,0x20,0x6f,0x6e,0x0d,0x0a,0x75,0x70,0x20,0x74,0x68,0x65,0x20,0x77, 0x65,0x62,0x0d,0x0a,0x61,0x6e,0x64,0x20,0x73,0x6d,0x69,0x6c,0x65,0x64,0x0d,0x0a, 0x3a,0x29 }; const int poem_size = (int)sizeof(poem); int main( ) { MEM_FILE fp; OpenFileInMemory( &fp, poem ); // prints: // the spider crawled on up the web and smiled :) while ( fp.bytes_read < poem_size ) { char buffer[ 256 ]; fscanf( &fp, "%s", buffer ); printf( "%s ", buffer ); } }