c++ - 如何从 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 作为响应。
如何获得正确的价值而不是根?
解决方案
推荐阅读
- java - 代码中的许多其他 if 语句
- matlab - Matlab如何将dbm转换为瓦特
- java - TextView NULL 指针异常
- android-source - ActivityStack 和 TaskRecord 有什么区别
- java - 带有 continue 或 break 的 if 语句
- c++ - 如何找到最大长度间隔,即开放间隔的总和?c/c++
- php - Nginx - 如何将所有 404 请求代理到不同的服务器
- c# - 如何正确地从控制器返回视图?
- mysql-workbench - SQL WHERE 子句不适用于字符串
- c++ - 如何将重载的 ostream 运算符与指向对象的指针数组一起使用?