0

I already know how to set a relative working directory path and access resources inside of visual studio. However, when I build my solution and move the exe to a separate file I have to include all the resources in the same directory as the exe. I'd prefer to have a folder with said resources alongside the exe to keep things clean. Is there a macro I need to use? Is the working directory the right setting to change for this?

example

Sorry for this incredibly basic question, but I think I lack the vocabulary to accurately describe the issue.

  • 1
    Working directory would work assuming you set it to where the executable actually is, that being said you could also [get the path of the executable](https://stackoverflow.com/questions/1528298/get-path-of-executable) and use that as a base path (unfortunately this is OS specific afaict) – Borgleader Jun 19 '22 at 03:36
  • Long time since I've done any Win32 programming but it always used to be possible to incorporate resources into the exe file itself. – john Jun 19 '22 at 04:44

1 Answers1

0

For a Windows solution, GetModuleFileName to find the exact path of your EXE. Then a simple string manipulation to make a resource path string.

When you program starts, you can use this to ascertain the full path of your EXE.

std::string pathToExe(MAX_PATH, '\0');
GetModuleFileName(nullptr, szPathToExe.data(), MAX_PATH); // #include <windows.h> to get this function declared

On return, szPathToExe will be something like "C:\\Path\\To\\Your\\Program\\Circle.exe"

Then strip off the file name to get the absolute path

std::string resourceFolderPath = szPathToExe;
size_t pos = strPath.find_last_of("\\");
strPath = strPath.substr(0, pos+1); //+1 to include the backslash

Then append your resource folder name and optionally another trailing backslash.

resourceFolderPath += "res\\";

Then change all your I/O calls to open files relative to resourceFolderPath

You should probably add reasonable error checking to the above code such as validating the return code from GetModuleFileName and find_last_of calls.

selbie
  • 100,020
  • 15
  • 103
  • 173
  • After obtaining the path from `::GetModuleFileNameW()`, instead of direct string manipulation, you could use C++ filesystem library facilities, such as [`std::filesystem::path::replace_filename()`](https://en.cppreference.com/w/cpp/filesystem/path/replace_filename). – heap underrun Jun 19 '22 at 10:26