The #include
directive simply copies the contents of another file into your source code before it is converted into an executable by the C compiler. In other words, it's a one time process, with the other file "baked into" your code.
If you need to re-load the contents of a file "dynamically" each time the program is run, you'll need to load it in yourself using C code. Here's an example, pulled from one of my own projects:
/*
[PUBLIC] Load the contents of a file into a malloc()'d buffer.
*/
unsigned char *txtLoadFile(const char *file_name, long *length)
{
FILE *fsrc = NULL;
unsigned char *data = NULL;
long size = 0;
/* Attempt to open the requested file. */
fsrc = fopen(file_name, "rb");
if (!fsrc) { return NULL; }
/* Get the length of the file in bytes. */
fseek(fsrc, 0, SEEK_END);
size = (long)ftell(fsrc);
rewind(fsrc);
/* Copy the data into memory (with an extra zero byte, in case it's text). */
data = (unsigned char*)malloc(size + 1);
if (data)
{
memset(data, 0, size + 1);
fread(data, 1, size, fsrc);
}
fclose(fsrc);
/* Return the result. */
if (length) { *length = size; }
return data;
}
This code should be largely self-explanatory, but there are a few things worth pointing out:
- The file is being opened in
rb
(read-binary) mode - you may need to use r
(read-text) instead, depending on what you're doing. If so, you'll probably want to store the data using a plain char*
rather than an unsigned char *
as I've done here.
- An extra byte is allocated for the zero NULL-terminator character of the string.
- The buffer is being stored in dynamically-allocated memory. Since you seem to be more familiar with dynamic languages such as Python or Ruby, I should remind you that you will need to
free()
the allocated memory once you're done with it.