'How to read a file from a specific directory within a CMake project and without hardcoded paths
Intro
I have a subdirectory inside my src/-directory called game_engine. In game_engine I place game_engine-related classes which needs the content of files like shaders or OpenCL/Cuda-kernels that are placed in another or the same directories.
Problem
How to read the content of a file from a C++-class without using hardcoded absolute paths? The returned content must be a C-Style string.
What I have did so far?
I programmed the following helper function
char* read_source_code(const char *filename) {
std::fstream file(filename);
std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
return const_cast<char *>(content.c_str());
}
This only seems to work if I pass the absolute filename. In addition, my IDE displays the following warning: Address of stack memory associated with local variable 'content' returned
I also tried to construct the absolute path at runtime, but the functions that I used returned me the path to the CMake-debug directory. So I decided to ask stackoverflow for help.
Additional information
- I want to call the function read_source_code inside any class that needs the content of another file placed in arbitrary directory of my CMake project.
- Hard coded file paths are not allowed, because it has to work also for other teammates.
- I don't want the warning to appear anymore because it seems legitimate. I probably programmed a bug.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
