Does C++17 offer any way to load/read a file at compile time? More specifically, I want to load a file's content into a const char*
or std::string_view
, etc. For example:
constexpr const char* read_file_content(const char* file_path) {
/* should read in the content of the file and return it */
return "";
}
constexpr const char* file_path = "some/folder/file.json";
constexpr const char* file_content = read_file_content(file_path);
I've come across this answer Is it possible to read a file at compile time? from 2014. The solution by teivaz works perfectly, using some macro & #include
magic. However, it requires the input file to be changed: the file should enclose its content in STR( ... ), which may not always be possible.
Since the above answer is quite old, I thought maybe things have changed, and perhaps C++17 (or possibly C++20) offers some functionality to overcome this issue.
C++20 might ship with std::embed
. Have a look at P1040. If this lands, you can
constexpr std::span<const std::byte> someBytes = std::embed("pathToFile");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With