write files to header files?

Started by
4 comments, last by the_edd 15 years, 4 months ago
i have this file that contains ascii characters not viewable by text editors and i need to use it in my project. instead of reading from the file, could i include it as a header? write an array like my_file[] = {type out the data}; problem is, what would the "type out the data" part look like? thanks in advance
Advertisement
What does the data represent?

If it is a constant, then you could use a tool to transform it into a file which can be included into your project (it should be quite easy to write such a tool). If it is not conceptually constant, read the data at runtime.
it is constant always

<edit>
i figured it out. found a tool called bin2h which converts the file to header which was exactly what i needed

thanks again
You can include non-printable characters in a character array in a few different ways. First you can use escape sequences:
const char data[] = "\x54"; const char data[] = "\124"; // same string

Alternately, you can use integral values to initialize the array rather than a string literal:
const char data[] = { 0x54, 0x00 };
I used a technique to "include" a sound file in a game I made, which I wanted to be completely independent of external files. What I did was to write a program that converted the file (in my case an ogg-file) to a header that declared a char array. The char array is filled with numbers instead of characters, so non-visible characters is not a problem.

Here is the code for the program:
#include <iostream>#include <fstream>#include <algorithm>#include <string>using namespace std;int main(int argc, char *argv[]){	if(argc > 1)	{		string outfile(argv[1]);		outfile = outfile.substr(0, outfile.rfind('.'));		ifstream input(argv[1], ios::binary);		ofstream output((outfile + ".h").c_str(), ios::binary);		if(input.is_open() && output.is_open())		{			string header = outfile;			transform(header.begin(), header.end(), header.begin(), ::toupper);			output << "#ifndef " << header << endl;			output << "#define " << header << endl;			output << "const char " << outfile << "[] = \{";						char c;			input.get(c);			output << static_cast<int>(c);			while(input.get(c))			{				output.put(',');				output << static_cast<int>(c);			}			output << "};\n#endif" << endl;		}	}	else	{		cout << "Usage: ogg2h inputfile" << endl;	}}

It's just something that I hacked together quickly, but it worked fine for my purposes. Perhaps it might be of some use for you too.
I made a tool to do this. You can embed as many files as you like in a program and access them through an iterator or istream interface.

Check it out.

I don't recommend embedding loads of stuff in there, but it's useful for icons and things like that.

This topic is closed to new replies.

Advertisement