My program needs to read/write a text (just a few lines) file with its settings to disk. To specify a path in code may work well on one platform, like windows, but if runs it on Linux, the path is not cross platform.
I am looking for a similar solution to QSettings
that saves settings to different paths or has its native ways to handle this. Programmers don't need to do with the details. But the text file is not suitable to be saved as a value in QSettings
.
No user interaction should be needed to obtain such path. The text file should persist across application restarts. It can't be a temporary file.
Is there an existing solution in Qt and what is the API that should be used?
The location of application-specific settings storage differs across platforms. Qt 5 provides a sensible solution via
QStandardPaths
.Generally, you'd store per-user settings in
QStandardPaths::writableLocation(QStandardPaths::AppDataLocation)
. If you wish the settings not to persist in the user's roaming profile on Windows, you can useQStandardPaths::AppLocalDataLocation
, it has the meaning ofAppDataLocation
on non-Windows platforms.Before you can use the standard paths, you must set your application name via
QCoreApplication::setApplicationName
, and your organization's name usingsetOrganizationName
orsetOrganizationDomain
. The path will depend on these, so make sure they are unique for you. If you ever change them, you'll lose access to old settings, so make sure you stick with name and domain that makes sense for you.The path is not guaranteed to exist. If it doesn't, you must create it yourself, e.g. using
QDir::mkpath
.You can store file in application directory. Take a look at
QCoreApplication::applicationDirPath()
.From Qt documentation:
If you want to save some user related data, you can get user home directory path using
QDir::homePath()
.There is
QDir
to handle paths to dirs,QFileInfo
for platform independent file information andQDir
'shomePath()
My proposal is to use these classes and use
QDir::home()
orQDir::homePath()
to find a directory where to write to, since the user has write permissions in his homedir and it exists on each platform.