c++g++precompiler

Use file content as hardcoded string


I'm looking for an easy way to use the content of a file as hardcoded string constant.

Of course i could just copy/paste the file content into an define but that would require me to put \s at the end of each line and in front of each ".

I tried to use constexpr to make the precompiler load the file but either i did something wrong(i'm not familiar with constexpr) or it is not possible that way.

Here is what i tried:

constexpr const char* loadFile()
{
    std::string retVar;

    std::ifstream file("filename.txt");
    retVar = std::string((std::istreambuf_iterator<char>(file)),
                     std::istreambuf_iterator<char>());

    return retVar.c_str();

}

#define FILE_CONTENT = loadFile();

I get the error:

error: body of constexpr function 'constexpr const char* loadFile()' not a return-statement

Maybe someone can modify my code to work as expected or maybe someone has an entirely new way to achieve my goal.

I know i could simply write a script which reads the content of a file and converts it into a #define but i would like to do it without additional pre-build steps.

Edit: How to embed a file into an executable? focuses on embedding binary files. I just want to use a text file's content as hard coded string. The methods suggested there are way too heavy for what i want to do.


Solution

  • The easiest way is to indeed copy-paste the content into your header/implementation file, but as a raw string literal, i.e.

    constexpr const char *fileContent = R"~(FILE_CONTENT_GOES_HERE)~";
    //               begin raw literal: ^^^^                      ^^^ end raw literal
    

    where you should replace FILE_CONTENT_GOES_HERE with the unmodified content of the file. Note that the delimiter (here: ~) can be chosen differently, see here for the details.

    Raw string literals are a C++11 feature that frees you from the necessity to escape anything (quotation marks, newlines etc.). Note that with C++17, you might want to optionally bind the string literal to a std::string_view instance and/or declare the variable as inline.