在字符串中引用Linux用户名以打开文件 [英] Reference Linux username in string to open file
本文介绍了在字符串中引用Linux用户名以打开文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个配置文件,其中包含另一个需要打开的文件的路径.此文件路径引用Linux用户名:
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
其中$ USER应该转换为Linux用户名.
where $USER should be translated to the Linux username.
这不起作用,因为该字符串存储在我的配置文件中,所以我不能使用getenv()
.
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?
推荐答案
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.
但是我通常这样使用std::getenv()
:
auto HOME = std::getenv("HOME"); // may return nullptr
auto USER = std::getenv("USER"); // may return nullptr
这篇关于在字符串中引用Linux用户名以打开文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文