Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt read files from Resources Bundle Directory

Tags:

c++

macos

cmake

qt

I have a Qt program, that has some .txt files inside. In the beginning I just read them from some directory I made, but the time has come, and it become necessary to create a bundle for Mac OSX. I managed to put .txt files inside /Resources in .app directory of bundle with the help of cmake, but I didn't find how to read them from there.

How can I read those files, so I could run that app from everywhere?

like image 430
fminkin Avatar asked Sep 12 '25 17:09

fminkin


1 Answers

As @MrEricSir pointed out, it's better to use the Qt resource system along with the native Qt classes for reading files via streams.

However, if you still need to store your data in the separate files, you can simply use the QCoreApplication::applicationDirPath() method which returns the path to the executable and wrap it into your own function in order to respect the application structure on different platforms.

For example:

QString getResourcesPath()
{
#if defined(Q_OS_WIN)
    return QApplication::applicationDirPath() + "/";
#elif defined(Q_OS_OSX)
    return QApplication::applicationDirPath() + "/../Resources/";
#elif defined(Q_OS_LINUX)
    return QApplication::applicationDirPath() + "/../share/yourapplication/";
#else
    return QApplication::applicationDirPath() + "/";
#endif
}

This sample code assumes that:

  • On Windows you are storing resources in the same directory as your executable.
  • On macOS you are storing resources in the Resources directory of your .app bundle. According to the Apple developer docs, executables are stored in the yourapplication.app/Contents/MacOS directory and resource files are usually stored in the yourapplication.app/Contents/Resources. The code simply travels to the Resources directory relatively to your executable.
  • On Linux you are using the standard Linux directory structure utilizing the separate bin and share directories. Of course, you may use the opt directory or don't bundle your application at all – in this case you won't need any conditional inclusions for Linux. For more information read about the Linux Filesystem Hierarchy Standard.
like image 83
kefir500 Avatar answered Sep 15 '25 08:09

kefir500