首页 > 解决方案 > 如何从 Cmake 项目中的 cpp 获取用户名?

问题描述

我正在尝试获取用户名。即,它相当于whoami在 ubuntu 机器中。但我无法得到。我试过以下片段。

方法一:

std::string get_username() {
    struct passwd *pwd = getpwuid(getuid());
    if (pwd)
        return pwd->pw_name;
    else
        return "(?)";
}

方法二:

#include<iostream>
#include <cstdio>
using namespace std;
int main()
{
    char text[255];
    FILE *name;
    name = popen("whoami", "r");
    fgets(text, sizeof(text), name);
    cout << "Name is : " << text;
    pclose(name);
    cout << endl;
    return 0;
}

方法3:

#include <iostream>
#include <stdlib.h>
using namespace std;
int main() {
    cout << getenv("USER") << endl;
    cout << getenv("HOME") << endl;
    return 0;
}

所有方法都按我的预期返回值。但是,当我将此代码集成到我的 Cmake 项目中时,它总是返回root. 我很困惑为什么我在尝试使用 Cmake 时总是得到 root 作为响应。

如何获得正确的价值而不是根?

标签: c++clinuxcmake

解决方案


推荐阅读