问题
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