-1

I have a config file which contains the path to another file which needs to be opened. This file path references the Linux username:

/root/${USER}/workspace/myfile.txt

where $USER should be translated to the Linux username.

This doesn't work and because the string is stored in my config file, I cannot use getenv().

Is there another way to achieve this?

user997112
  • 29,025
  • 43
  • 182
  • 361

2 Answers2

2

You can use wordexp to translate "~" which is a UNIX path element meaning the HOME directory. Something like this:

#include <wordexp.h>

std::string homedir()
{
    std::string s;
    wordexp_t p;
    if(!wordexp("~", &p, 0))
    {
        if(p.we_wordc && p.we_wordv[0])
            s = p.we_wordv[0];
        wordfree(&p);
    }
    return s;
}

And then extract the username from the returned path.

But I normally use std::getenv() like this:

auto HOME = std::getenv("HOME"); // may return nullptr
auto USER = std::getenv("USER"); // may return nullptr
Galik
  • 47,303
  • 4
  • 80
  • 117
2

Get the username with getenv, replace $USER in the path with it.

Very straightforward example:

#include <iostream>
#include <string>
#include <cstdlib>

int main()
{
    std::string path = "/root/$USER/workspace/myfile.txt";
    const char* user = std::getenv("USER");
    int pos = path.find("$USER");
    if (user != nullptr && pos >= 0)
    {
        path.replace(pos, 5, user);
        std::cout << path << std::endl;
    }
}
molbdnilo
  • 64,751
  • 3
  • 43
  • 82