SFML community forums

Help => Graphics => Topic started by: abcnb on October 20, 2022, 02:09:38 pm

Title: Failed to load image in MSVC
Post by: abcnb on October 20, 2022, 02:09:38 pm
This
t1.loadFromFile("images/red.png");
:
1. Compiles.
2. Runs from Debug or Release directory.
3. Doesn't run inside MSVC.

This
t1.loadFromFile("C:\\Users\\User\\source\\repos\\SFMLtest\\x64\\Debug\\images\\red.png");
 
:
Works correctly in all cases.

Can somebody tell how to do it properly?
Title: Re: Failed to load image in MSVC
Post by: kojack on October 20, 2022, 03:11:25 pm
SFML's load functions are relative to the working directory of the program (when you don't give it an absolute path like "C:\\")
When you run a program from explorer, the working directory is set to where the exe file is.

Running a program from inside Visual Studio uses the working directory set in the project properties. Annoyingly, VS defaults all projects to having a working directory of where the vcxproj file is, instead of where the exe file is.

There's two ways to fix this:
1 - Go into project properties, Configuration Properties / Debugging / Working Directory and change it from $(ProjectDir) to $(TargetDir)
(TargetDir is the directory with the exe file, ProjectDir is the directory with the vcxproj file)
2 - Use Win32 to ask for the directory of where the program (the exe) is and change the working directory to that.

This is the code I use for the second option (since otherwise I always forget to change the project properties):
        char buf[MAX_PATH];
        GetModuleFileName(NULL,buf,MAX_PATH);

        std::string filename(buf);
        size_t backslash = filename.find_last_of('\\');
        if (backslash != std::string::npos)
        {
            filename = filename.substr(0, backslash);
        }
        SetCurrentDirectory(filename.c_str());
 

Sometimes you might want the ability to set different working directories externally, the second method will cancel out that and might therefore be unwanted.
Title: Re: Failed to load image in MSVC
Post by: abcnb on October 21, 2022, 06:46:35 am
Really many-many thanks. I assume that this is an offtopic about MSVC not SFML, but your answer with looking on projects settings from https://www.sfml-dev.org/download/sfml/2.5.1/ after CMake help so much.