The simplest thing in this sort of case is to write a small
preprocessor, which reads your file, and outputs it wrapping
each line in quotes. I'd probably do this in Python, but it is
pretty straight forward in C++ as well. Supposing that you've
got inputFile
, outputFile
and variableName
from
somewhere (probably argv
, but you might want to derive the
latter two from the input filename:
void
wrapFile( std::istream& inputFile,
std::ostream& outputFile,
std::string const& variableName )
{
outputFile << "extern char const " << variableName << "[] =\n";
std::string line;
while ( std::getline( inputFile, line ) ) {
outputFile << " \"" << line << "\\n\"\n";
}
std::outputFile << ";" << std::endl;
}
Depending on what is in the files you're including, you might
have to mangle the line
before outputting it, to escape things
like "
or \
.
If you wanted to get fancy, you could add some tests to insert
the semicolon on the last wrapped line, rather than a line of
its own, but that's not really necessary.
This will result in a '\0'
terminated string. Given the
probable length of the strings, it might be preferable to add
a second variable with the length:
std::outputFile << "extern int const "
<< variableName
<< "_len = sizeof(" << variableName << ") - 1;\n";
(Don't forget the -1, since you don't want to count the
terminating '\0'
that the compiler will add to your string
literal.) If you're including the generated file where it will
be used, you don't necessarily need this, since std::begin
and
std::end
will provide the necessary information (but again,
don't forget to use std::end( variableName ) - 1
, to ignore
the '\n'
).
If you're using make
, it's fairly easy to make your generated
file depend on the file being wrapped, and the executable
which does the wrapping (which in turn depends on the source
above, etc.). With Visual Studios, you'll need to create
a separate project for the wrapping code, if you write it in C++
(one of the reasons I'd use Python for this), and you'll likely
have some problems with dependency management; Visual Studios
isn't really designed for professional work (where large blocks
of code are regularly generated using such techniques).