Reputation: 18173
I need to obtain the current user's home directory and then append to it paths to other directories. Since the app is cross-platform then the approach should take this into consideration. I have been looking for a solution without success. Is there a way to get current user's home directory using C++17 std::filesystem?
Upvotes: 8
Views: 4552
Reputation: 2495
On Windows:
#include <filesystem>
#include <ShlObj_core.h>
#include <Windows.h>
std::filesystem::path get_home_folder()
{
PWSTR homeDir = nullptr;
SHGetKnownFolderPath(FOLDERID_Profile, KF_FLAG_DEFAULT, nullptr, &homeDir);
std::filesystem::path result { homeDir };
CoTaskMemFree(homeDir);
return result;
}
Upvotes: 0
Reputation: 81
Simple:
#include <iostream>
#include <unistd.h>
int main() {
char *homeDir = getenv("HOME");
if (homeDir != nullptr) {
std::cout << "Home directory: " << homeDir << std::endl;
} else {
std::cerr << "Error getting home directory." << std::endl;
}
return 0;
}
Upvotes: 1
Reputation: 275820
No.
The only special directories you are handed is a directory suitable for temporary files, and the current directory.
You'll have to write a OS specific wrapper for getting the home directory. I, personally, think that is a bad idea: rather, you should have "user app settings" directory function, "user document'" directory function, etc (as determined by your application needs). Where those directories are compared to the home directory vary on a OS by OS basis.
In my experience, also having an API for storing a "registry-like property set" is a good idea (a string-string map with serialization code on the values, for example). It can map to plists on macOS, registry on windows, and something else on linux.
Upvotes: 6