how to expand the tilde (~) home in a path with std::filesystem

87 Views Asked by At

I'm trying to use the std::filesystem to expand the tilde (~) in a path.

for example:

convert "~/Desktop" to "/homes/thewoz/Desktop"

know how I can do?

Update:

Thank you all for your responses. Anyway it seems to me that the answer is NO.
I was asking if there was a way to do it with std::filesystem not a generic way to do it.

1

There are 1 best solutions below

4
folibis On

maybe like this:

std::string expand_home_dir(const std::string &path)
{
    char *dir = std::getenv("HOME");
    size_t index = 0;
    std::string retval = path;

    if (dir != nullptr) {
        std::string replace(dir);

        while (true) {
            index = retval.find("~", index);
            if (index == std::string::npos) {
                break;
            }

            retval.replace(index, 1, replace);
            index += replace.size();
        }
    }

    return retval;
}

For Windows it's probably a concatenation of std::getenv("HOMEDRIVE") and std::getenv("HOMEPATH"), I have no way to verify this.