Reference Linux username in string to open file

那年仲夏 提交于 2019-12-08 13:54:18

问题


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?


回答1:


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



回答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;
    }
}


来源:https://stackoverflow.com/questions/52255940/reference-linux-username-in-string-to-open-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!