PDA

View Full Version : Please critique my application directory function.



LZAntal
18th January 2013, 16:35
Hi all,

My app needs to read configuration files relative to the application directory. I'm on mac and QDir::current() was returning the directory inside the bundle. I found the code below in the docs here (http://doc.qt.digia.com/qt/mac-differences.html) and I wrote a function to use with the addition of falling back to QDir::current if it's not mac.
It works great on the mac I don't have access to windows or linux at the moment to test
Since I'm very new to Qt please let me know if the there is any mistake there or if you would approach it differently.
Also if anyone could test it on windows and/or linux to see what it returns I would greatly appreciate it.



#ifdef Q_OS_MAC
#include "CoreFoundation/CoreFoundation.h"
#endif

QString AppDir(){
#ifdef Q_OS_MAC
CFURLRef appUrlRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
CFStringRef macPath = CFURLCopyFileSystemPath(appUrlRef,
kCFURLPOSIXPathStyle);
const char *pathPtr = CFStringGetCStringPtr(macPath,
CFStringGetSystemEncoding());
CFRelease(appUrlRef);
CFRelease(macPath);
QString filePath = QString(pathPtr);
QString dirPath = filePath.left(filePath.lastIndexOf("/"));
return dirPath;
#else
QDir appdir = QDir::current();
return appdir.path();
#endif
}


Thank you

Laszlo

wysota
18th January 2013, 16:48
What was wrong with QCoreApplication::applicationDirPath()?

LZAntal
18th January 2013, 16:52
Hi,

It returns the directory inside the bundle Eg: UserDir/MyApp.app/Contents/MacOS which is not what I'm after.
I need the UserDir so users can place configuration files in there next to the app and if it exists the app loads them otherwise it loads the defaults from resources.

Laszlo

wysota
18th January 2013, 17:13
Well... QDir::current() will simply not work. It returns the current working directory which has nothing to do with the application directory.

Placing configuration in the directory containing the bundle is probably a bad idea. What if the bundle is placed somewhere the user has no access rights to? Configuration should be placed somewhere under user's home directory. Otherwise there are too many things that could fail.

LZAntal
20th January 2013, 17:33
Hi,

You're correct. If the application is deployed to the default Applications folder or other default app directory it wont work.
However I am writing a host for my gamelib RaptorGL.com. So the app wont be in an application folder rather in the game project directory. When a suer supplied settings.json can't be loaded it loads a default one from Resources, which btw is rockin my world :)

So with that background do you see anything in there that could cause issues in other platforms?

Thank you for your help

Laszlo

wysota
20th January 2013, 18:06
I told you, QDir::current() won't work.