1

I'm attempting to change the working directory so I can access a png I put in a folder next to the executable. Here's the code:

std::string ExePath() {
    char buffer[MAX_PATH];
    GetModuleFileName(NULL, buffer, MAX_PATH);
    std::string::size_type pos = std::string(buffer).find_last_of("\\/");
    return std::string(buffer).substr(0, pos);
}

int main()
{
    sf::RenderWindow window(sf::VideoMode(600, 600), "Meatboy experiment");
    sf::Texture meatboyT;
    if (!meatboyT.loadFromFile("sprites\meatboy.png")) {
        std::cout << ExePath() << std::endl;
    }
    .
    .
    .

I right click on the project name and click on properties. under debugging, I set the Working directory to $(SolutionDir)$(Configuration)\.

When I run it the output is c:\users\joseph\source\repos\experiment\x64\Debug which is two folders deeper than I wanted.

I change the working directory again, to C:\Users\Joseph\source\repos\experiment\experiment

the output is still c:\users\joseph\source\repos\experiment\x64\Debug. Why?

  • 2
    I don't think you are checking the working directory correctly. `GetModuleFileName` returns the path of the executable. In C++17 the working directory is available via `std::filesystem::current_path`, otherwise for Windows see: https://stackoverflow.com/questions/4807629/how-do-i-find-the-current-directory –  Nov 27 '18 at 00:10
  • 1
    `...\x64\Debug` is the folder where VS outputs your compiled EXE. That is different than the "working directory". You don't need to mess around with the working directory at all. You know the path to the executable (`GetModuleFileName()` gives you that), simply strip off the trailing filename and any additional parent folders as needed, then append the desired subfolder and PNG filename. The Win32 API even has functions to help you with that (`PathRemoveFileSpec()`, `PathCombine()`, `PathCanonicalize()`, etc). If you really want the actual "working directory", use `GetCurrentDirectory()` – Remy Lebeau Nov 27 '18 at 01:55

0 Answers0