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?
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:
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.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.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With