views:

83

answers:

4

I want to embed a file in a program. It will be used for default configuration files if none are provided. I have realized I could just use default values, but I want to extract the file and place it on the disk so it can be modified.

A: 

If it's any Unix look into mapping the file into process memory with mmap(2). Windows has something similar but I never played with it.

Nikolai N Fetissov
I don't think you've answered the right questions here...
dmckee
I was answering the left ones :)
Nikolai N Fetissov
+2  A: 

By embedding do you mean distributing your program without the file?

Then you can convert it to configuration initialization code in your build toolchain. Add a makefile step (or whatever tool you're using) - a script that converts this .cfg file into some C++ code file that initializes a configuration data structure. That way you can just modify the .cfg file, rebuild the project, and have the new values reflected inside.

By the way, on Windows, you may have luck embedding your data in a resource file.

Eli Bendersky
Well what I'm really trying to do is have an my program be able to generate a valid file, for example a .png file, from within the engine. I want to be able to then generate these files onto the disk, sort of like a zip file.
Jeff
+2  A: 

Embedded data are often called "resources". C++ provides no native support, but it can be managed in almost all executable file formats. Try searching for resource mangers for c++.

dmckee
+1  A: 

One common thing you can do is to represent the file data as an array of static bytes:

// In a header file:
extern const char file_data[];
extern const size_t file_data_size;

// In a source file:
const char file_data[] = {0x41, 0x42, ... };  // etc.
const size_t file_data_size = sizeof(file_data);

Then the file data will just be a global array of bytes compiled into your executable that you can reference anywhere. You'll have to either rewrite your file processing code to be able to handle a raw byte array, or use something like fmemopen(3) to open a pseudo-file handle from the data and pass that on to your file handling code.

Of course, to get the data into this form, you'll need to use some sort of preprocessing step to convert the file into a byte array that the compiler can accept. A makefile would be good for this.

Adam Rosenfield
There are programs around that will translate data files into a pair of C files (header and body) for you. There's probably also programs that can pack data directly into linker object files, but obviously that's a less portable hack.
Steve314