I am trying to display an empty window in C++ using the SFML library. However, it gives me an error when I am loading an image with loadFromFile.
Failed to load image "enemy.png". Reason: Unable to open file
The image, "enemy.png" is in the source files directory (Using Visual Studio 2019), as well as the main.cpp file. I have downloaded the SFML x64-bit files and used dynamic linking through the project properties. I have tried to remove the load image part, and that successfully loads the window. But this isn't good because it won't work if I need to load a picture next time.
Here is the code:
#include <SFML/Graphics.hpp>
int main() {
float windowHeight = 400;
float windowWidth = 400;
sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), "Rougelike");
sf::Texture texture;
if (!texture.loadFromFile("enemy.png")) {
return 0;
}
sf::Sprite sprite;
sprite.setTexture(texture);
while (window.isOpen()) {
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::Closed) {
window.close();
}
}
window.clear();
window.draw(sprite);
window.display();
}
}
After running the code, this is what I get from the output:
Build started...
1>------ Build started: Project: Project1, Configuration: Debug x64 ------
1>main.cpp
1>D:\XXX\XXX\Project1\Project1\main.cpp(7,56): warning C4244: 'argument': conversion from 'float' to 'unsigned int', possible loss of data
1>D:\XXX\XXX\Project1\Project1\main.cpp(7,43): warning C4244: 'argument': conversion from 'float' to 'unsigned int', possible loss of data
1>Project1.vcxproj -> D:\XXX\XXX\Project1\x64\Debug\Project1.exe
1>Done building project "Project1.vcxproj".
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
And this is what I get from the command prompt:
Failed to load image "enemy.png". Reason: Unable to open file
D:\XXX\XXX\Project1\x64\Debug\Project1.exe (process 19768) exited with code 0.
Press any key to close this window . . .
Thanks.
You do not specify the path to you png
file, so the "current working directory" is used. This is NOT reliable, as the Visual Studio may use the project folder or something else. You can also change that in the Progect's properties.
For Windows, I suggest to keep your assets in the path relative to the folder containing executable file. Then you can always get that path at runtime using GetModuleFileName.