TTF_OpenFont cannot find the font.

I have initialized the SDL_ttf, but TTF_GetError says the font cannot be found. It is:
gFont = TTF_OpenFont(“FlightChess/append/kust.ttf”, 18);
SDL_ttf Error: Couldn’t open FlightChess/append/kust.ttf
I have put the ttf file in the append.

You’re using a relative path.

Relative paths are looked up in the “working directory” of the process.

The working directory can differ depending on how you started your program.

  • If you use the file browser and double click on the executable file the working directory will be the directory that contains the executable file.
  • If you use the terminal/command prompt the working directory will be the directory that you have navigated to using the cd command.
  • If you start your program from within an IDE, then it depends on the IDE, but usually it’s the “project directory”.

So what you might want to do is to use absolute paths instead.

You can use SDL_GetBasePath() to get the directory of the executable file.

This is not necessarily where you should always be looking for your data files though. For example on Linux you might want to follow the XDG Base Directory Specification (you might still want to fall back on the directory of the executable file in case the program is executed without being installed properly).

2 Likes

Thanks for your reply. But I still have some confusions:
I have put the relative path in the working directory. By using SDL_GetBasePath(), I find the directory is /Users/wangziyue/Library/Developer/Xcode/DerivedData/FlightChess-bomgmqsedhrzmqgyrpqajrqewhub/Build/Products/Debug/Failed to load the font! Does it mean I don’t store in this way ?
I start my program with an IDE, but it warns me it cannot find the font.(though the process is correct?)
FlightChess is the project.

Thank you very much.
I have solved this problem, I think it is because I regulate more process to find the ttf file.
Thank you!
wrote by: Wang Ziyue