gpt4 book ai didi

c++ - 获取计算机名和登录用户名

转载 作者:IT老高 更新时间:2023-10-28 22:15:50 25 4
gpt4 key购买 nike

我正在开发一个应用程序。其中一种方法需要捕获计算机名和登录机器的用户,然后将两者显示给用户。我需要它在 Windows 和 Linux 上运行。最好的方法是什么?

最佳答案

Windows

你可以尝试使用GetComputerNameGetUserName,这里是一个例子:

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

见:GetComputerNameGetUserName

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com