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?
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.