我有一个关于 getlogin() 函数 () 的问题。我试图使用此功能从 c 程序中获取我的帐户的登录名。但是该函数返回 NULL。使用 perror 显示错误是“没有这样的文件或目录”。
我不明白这是什么问题。有没有办法在程序中获取用户登录名。
这是一个示例代码:
#include <stdio.h>
#include <unistd.h>
int main()
{
char *name;
name = getlogin();
perror("getlogin() error");
//printf("This is the login info: %s\n", name);
return 0;
}
这是输出:getlogin() error: No such file or directory
请让我知道如何做对。
谢谢。
最佳答案
getlogin
是一种不安全且已弃用的确定登录用户的方法。它可能试图打开登录用户的记录,可能是 utmp
或其他东西。确定您正在运行的用户(可能与登录用户不同,但几乎总是更好用)的正确方法是 getpwuid(getuid())
。
关于c - getlogin() c 函数返回 NULL 和错误 "No such file or directory",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4785126/