Locate path to file, given its filename or filepath suffix and possible dirs it might lie in. Function will also walk back MAX_DEPTH dirs from CWD to check for such a file path.
| 209 | //! Locate path to file, given its filename or filepath suffix and possible dirs it might lie in. |
| 210 | //! Function will also walk back MAX_DEPTH dirs from CWD to check for such a file path. |
| 211 | inline std::string locateFile( |
| 212 | const std::string& filepathSuffix, const std::vector<std::string>& directories, bool reportError = true) |
| 213 | { |
| 214 | const int MAX_DEPTH{10}; |
| 215 | bool found{false}; |
| 216 | std::string filepath; |
| 217 | |
| 218 | for (auto& dir : directories) |
| 219 | { |
| 220 | if (!dir.empty() && dir.back() != '/') |
| 221 | { |
| 222 | #ifdef _MSC_VER |
| 223 | filepath = dir + "\\" + filepathSuffix; |
| 224 | #else |
| 225 | filepath = dir + "/" + filepathSuffix; |
| 226 | #endif |
| 227 | } |
| 228 | else |
| 229 | { |
| 230 | filepath = dir + filepathSuffix; |
| 231 | } |
| 232 | |
| 233 | for (int i = 0; i < MAX_DEPTH && !found; i++) |
| 234 | { |
| 235 | const std::ifstream checkFile(filepath); |
| 236 | found = checkFile.is_open(); |
| 237 | if (found) |
| 238 | { |
| 239 | break; |
| 240 | } |
| 241 | |
| 242 | filepath = "../" + filepath; // Try again in parent dir |
| 243 | } |
| 244 | |
| 245 | if (found) |
| 246 | { |
| 247 | break; |
| 248 | } |
| 249 | |
| 250 | filepath.clear(); |
| 251 | } |
| 252 | |
| 253 | // Could not find the file |
| 254 | if (filepath.empty()) |
| 255 | { |
| 256 | const std::string dirList = std::accumulate(directories.begin() + 1, directories.end(), directories.front(), |
| 257 | [](const std::string& a, const std::string& b) { return a + "\n\t" + b; }); |
| 258 | std::cout << "Could not find " << filepathSuffix << " in data directories:\n\t" << dirList << std::endl; |
| 259 | |
| 260 | if (reportError) |
| 261 | { |
| 262 | std::cout << "&&&& FAILED" << std::endl; |
| 263 | exit(EXIT_FAILURE); |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | return filepath; |
| 268 | } |
no test coverage detected