I'm working on a C++14 application where I want to assign the entire contents of a text file to a std::string, stringstream, or char variable or structure. This is easy at runtime, but I want this to happen at compile-time or from a compiler macro (before runtime).
I do not want to use a pre-compile step with a script, cmake tricks, etc..
The text file will have characters such as '#' and '/' as well as letters and digits. There are linefeed characters as well.
Is there a way to do this in C++14? I've looked through Boost and could not find a way to do this before runtime. Large amounts of web-searching has not given me any hope either.
If there's not a way to do this in C++14 but one exists in C++17, that would be useful to know also.
I've seen this solution for run-time assignment of a string (the accepted answer to this question: Read whole ASCII file into C++ std::string). I've tried to make the variable str a constexpr but that won't compile because the ifstream is not a constant :
#include <string>
#include <fstream>
#include <streambuf>
std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
What I expect is to have the all of the characters in the file available in the string, stream, or character, with all of the files original characters (including the linefeed and other whitespace) in the same order as they occur in the file.
UPDATE:
Even incbin, as suggest in the comments, under MSVC (VS2015) requires a pre-compile step to process the file before adding it's binary form to the C++ application.
I've given up at this point and will use the following method:
1) process the file with a script to add the following string to the beginning of the file: R"(
2) have the script add the following to the end of the file: )"
3) use the following code to set a char variable:
constexpr char* const s1 =
#include "file.txt"
;
where file.txt is the modified file with the steps 1) and 2) above completed.
I can parse the data from that. I checked the output of a test program that uses the above code and sends the contents of s1 to the console to find all of the data, including the linefeeds. I also found the data in the .exe that VS2015 built.
The script that will do the work of steps 1) and 2) above will first check if R"( and )" are at the beginning and end of the file, respectively, before changing the file.
Thank you for the suggestions and the help!