代码之家  ›  专栏  ›  技术社区  ›  user997112

在字符串中引用Linux用户名以打开文件

  •  -1
  • user997112  · 技术社区  · 7 年前

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

    其中$USER应转换为Linux用户名。

    getenv() .

    有没有别的方法可以达到这个目的?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Galik    7 年前

    你可以用 wordexp 翻译“~”是 UNIX 表示主目录的path元素。像这样:

    #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;
    }
    

    但我通常用 std::getenv()

    auto HOME = std::getenv("HOME"); // may return nullptr
    auto USER = std::getenv("USER"); // may return nullptr
    
        2
  •  2
  •   molbdnilo    7 年前

    获取用户名 getenv $USER 在这条路上。

    非常简单的例子:

    #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;
        }
    }