I'm working on a GUI desktop application that should run natively on Windows, Mac OS X and Linux. What is the preferred way to store preferences in a cross-platform application? I'm using C++, but the question (and its answers) should be valid for any natively compiled language. (Solutions for dynamic languages and Java can be seen here.)
My research so far tells me, that there are at least two strategies:
(A) Use the OS-specific API preferences functions.
(B) Store the preferences in a file within an appropriate (OS-specific) folder.
Let's consider method (A): I assume NSUserDefaults
is the correct method for Mac OS X. On Windows systems, I'd write to the registry via RegOpenKeyEx
. But there arise some questions: Is there any comparable and portable Linux API for that? Is writing to the Windows registry really a future-proof solution?
To keep things simple, I'm inclined to follow method (B). Thus I just have OS-specific code to get the appropriate directory where I can store my data in a format of my choice. On Windows, I've learned SHGetFolderPath
(or SHGetKnownFolderPath
for recent Windows systems) and CSIDL_LOCAL_APPDATA
is the way to go. On Macs, the NSSearchPathForDirectoriesInDomains
API call should do the same; it's an Objective-C API though making things more complicated. Finally, for the Linux version using getenv("HOME")
(and getpwuid()
as a fallback solution) seems to be recommend.
To summarize my questions:
1. Are there any patterns considered as best-practice for this task?
2. Is there any C++ class abstracting all the dirty things like finding the correct folder away out there? (I came across QSetting, but I'm using FLTK and I don't want to change my GUI toolkit.)
Edit:
By "preferences" I mean data that may be changed by the application and the user, e.g. a list of recent files, the preferred window size and so on.
Usually to store user preferences, it is best to use localStorage. It does not have expiration so will be valid unless and until you clear it programatically or user clears it in browser manually .
User settings are generally saved locally in Android using SharedPreferences with a key-value pair. You use the String key to save or look up the associated value.
I'm also developing a set of cross-platform plugins and did exactly what you describe in method (B):
I would also note that:
~/Library/Preferences
folder directly but rather use their API for saving preferences value. In effect this turns the preferences into registry like mechanism. I very much resent this approach.I do not know of any library that implements finding the currect folder in cross-platform manner. Such function is not very hard to write using SHGetKnownFolderPath and NSSearchPathForDirectoriesInDomains, as you described.
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