Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Can't Load Fonts When Running from the Terminal  (Read 795 times)

0 Members and 1 Guest are viewing this topic.

cmfox

  • Newbie
  • *
  • Posts: 1
    • View Profile
Can't Load Fonts When Running from the Terminal
« on: June 11, 2022, 06:14:28 pm »
When I run the .exe directly it works perfectly fine, and everything loads accordingly. In addition, when I run "make" to build the project there are no errors. However, when I run ./bin/zombies I get an error:
Failed to load font "../assets/fonts/font.ttf" (failed to create the font face)

Here is the layout of my files:
/Zombies/bin/zombies.exe
/Zombies/assets/fonts/font.ttf
/Zombies/src/main.cpp

Here is the code I use in my .cpp file:
font.loadFromFile("../assets/fonts/font.ttf");

This means I can't debug with GDB since I can't run it from the terminal. Any idea on why this is?
« Last Edit: June 11, 2022, 06:18:14 pm by cmfox »

kojack

  • Sr. Member
  • ****
  • Posts: 314
  • C++/C# game dev teacher.
    • View Profile
Re: Can't Load Fonts When Running from the Terminal
« Reply #1 on: June 11, 2022, 06:49:10 pm »
Loading is relative to the current working directory, not the directory where the executable is.
So when you do ./bin/zombies it's trying to find /assets/fonts/font.ttf instead of /Zombies/assets/fonts/font.ttf.

What I do in my own SFML apps is find the directory of the executable and change the working directory to that, so where you run it from doesn't matter.

In Windows, this is what I do:
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); // strip off the file name from the path
        }
        SetCurrentDirectory(filename.c_str());
If you are on a different OS, you'll need a different method.