我正在开发一个应用程序。其中一种方法需要捕获计算机名和登录机器的用户,然后将两者显示给用户。我需要它在 Windows 和 Linux 上运行。最好的方法是什么?
最佳答案
Windows
你可以尝试使用GetComputerName
和GetUserName
,这里是一个例子:
#define INFO_BUFFER_SIZE 32767
TCHAR infoBuf[INFO_BUFFER_SIZE];
DWORD bufCharCount = INFO_BUFFER_SIZE;
// Get and display the name of the computer.
if( !GetComputerName( infoBuf, &bufCharCount ) )
printError( TEXT("GetComputerName") );
_tprintf( TEXT("\nComputer name: %s"), infoBuf );
// Get and display the user name.
if( !GetUserName( infoBuf, &bufCharCount ) )
printError( TEXT("GetUserName") );
_tprintf( TEXT("\nUser name: %s"), infoBuf );
见:GetComputerName 和 GetUserName
Linux
使用gethostname
获取计算机名(见gethostname),使用getlogin_r
获取登录用户名。您可以在man page of getlogin_r查看更多信息.
简单用法如下:
#include <unistd.h>
#include <limits.h>
char hostname[HOST_NAME_MAX];
char username[LOGIN_NAME_MAX];
gethostname(hostname, HOST_NAME_MAX);
getlogin_r(username, LOGIN_NAME_MAX);
关于c++ - 获取计算机名和登录用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27914311/