Amani
Amani

Reputation: 18173

How can one get user's home directory using C++17 std::filesystem?

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

Answers (3)

Burak
Burak

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

Todd Hill
Todd Hill

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

Yakk - Adam Nevraumont
Yakk - Adam Nevraumont

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

Related Questions