AppData / Similar for all OS : C++?

。_饼干妹妹 提交于 2020-07-10 01:45:32

问题


I'm looking to store some "preferences" for my C++ application.

Under windows I know I have to use the "AppData" folder, but I need the equivalent for Linux and OsX.

Is there some library or portable way to get such information in C++ ?

Here is the code I use currently:

#ifdef VD_OS_WINDOWS
    LPWSTR wszPath = NULL;
    HRESULT hr = SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_CREATE, NULL, &wszPath);

    _bstr_t bstrPath(wszPath);
    std::string strPath((char*)bstrPath);
    CoTaskMemFree(wszPath);

    return strPath;
#else
    char* path = getenv("XDG_CONFIG_HOME");
    if (!path)
        getenv("HOME") + ".local/share";

    return string(path);
#endif

Thanks


回答1:


If you happen to write a Qt application, there is the QSettings Class. The documentation says the following about this class:

The QSettings class provides persistent platform-independent application settings.

Users normally expect an application to remember its settings (window sizes and positions, options, etc.) across sessions. This information is often stored in the system registry on Windows, and in XML preferences files on Mac OS X. On Unix systems, in the absence of a standard, many applications (including the KDE applications) use INI text files.

This delivers IMHO the best "out-of-the-box" experience. And it's really platform independent.

An alternative would be boost::program_options or boost::property_tree. But the aim of these libraries is the data handling, not so much the storage. This means you would still need to detect the platform, and store the data in the correct location.




回答2:


Historically on Linux the program stores its configuration data in a hidden file or folder (one beginning with a dot .) in the $HOME directory.

So something like:

$HOME/.my_prog_data.conf

or

$HOME/.my_prog_data/config.conf

In a more recent effort to clean up the $HOME directory nowadays programs tend to either use $HOME/.config or $HOME/.local/share rather than $HOME itself.



来源:https://stackoverflow.com/questions/34006205/appdata-similar-for-all-os-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!