Skip to content

Instantly share code, notes, and snippets.

@MattSturgeon
Last active September 30, 2016 23:31
Show Gist options
  • Save MattSturgeon/8089e6aa723dc87813258b36ebf3896b to your computer and use it in GitHub Desktop.
Save MattSturgeon/8089e6aa723dc87813258b36ebf3896b to your computer and use it in GitHub Desktop.
A function to get the correct user config directory.
#include <cstdlib>
#include <string>
#include <iostream>
#define PROJECT_NAME "OpenBoardView"
//using namespace std;;
// on linux use $XDG_CONFIG_HOME || $HOME/.config
// on windows use %APPDATA%
// on OSX use $HOME/Library/Preferences
std::string get_config_dir() {
#ifdef __APPLE__
if (const char *home = std::getenv("HOME")) {
return std::string(home) + "/Library/Preferences/" PROJECT_NAME "/";
}
#elif defined _WIN32 || defined _WIN64
if (const char *appdata = std::getenv("APPDATA")) {
return std::string(appdata) + "\\" PROJECT_NAME "\\";
}
#else // Linux
if (const char *xdg_conf = std::getenv("XDG_CONFIG_HOME")) {
return std::string(xdg_conf) + "/" PROJECT_NAME "/";
}
if (const char *home = std::getenv("HOME")) {
return std::string(home) + "/.config/" PROJECT_NAME "/";
}
#endif
std::cerr << "Could not determin config directory!" << std::endl;
exit (1);
}
// on linux use $XDG_CACHE_HOME || $HOME/.cache
// on windows use %LOCALAPPDATA% || %APPDATA%
// on OSX use $HOME/Library/Caches
std::string get_cache_dir() {
#ifdef __APPLE__
if (const char *home = std::getenv("HOME")) {
return std::string(home) + "/Library/Caches/" PROJECT_NAME "/";
}
#elif defined _WIN32 || defined _WIN64
if (const char *localAppdata = std::getenv("LOCALAPPDATA")) {
return std::string(localAppdata) + "\\" PROJECT_NAME "\\";
}
if (const char *appdata = std::getenv("APPDATA")) {
return std::string(appdata) + "\\" PROJECT_NAME "\\";
}
#else // Linux
if (const char *xdg_cache = std::getenv("XDG_CACHE_HOME")) {
return std::string(xdg_cache) + "\\" PROJECT_NAME "\\";
}
if (const char *home = std::getenv("HOME")) {
return std::string(home) + "/.cache/" PROJECT_NAME "/";
}
#endif
std::cerr << "Could not determin cache directory!" << std::endl;
exit (1);
}
int main () {
std::cout << "get_config_dir: \"" << get_config_dir() << "\"" << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment