Mrd*_*rdk 16 c++ linux windows
我正在开发一个应用程序.其中一种方法需要捕获计算机名称和登录计算机的用户,然后向用户显示.我需要它在Windows和Linux上运行.做这个的最好方式是什么?
pez*_*ezy 22
视窗
你可以尝试用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 );
Run Code Online (Sandbox Code Playgroud)
请参阅:GetComputerName 和GetUserName
Linux的
使用gethostname得到计算机名称(见的gethostname),并getlogin_r获得登录用户名.您可以在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);
Run Code Online (Sandbox Code Playgroud)
Viv*_*vit 11
如果您可以使用Boost,则可以轻松获取主机名:
#include <boost/asio/ip/host_name.hpp>
// ... whatever ...
auto host_name = boost::asio::ip::host_name();
Run Code Online (Sandbox Code Playgroud)
在POSIX系统上,您可以使用gethostname和getlogin声明的和函数unistd.h.
/*
This is a C program (I've seen the C++ tag too late). Converting
it to a pretty C++ program is left as an exercise to the reader.
*/
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main()
{
char hostname[HOST_NAME_MAX];
char username[LOGIN_NAME_MAX];
int result;
result = gethostname(hostname, HOST_NAME_MAX);
if (result)
{
perror("gethostname");
return EXIT_FAILURE;
}
result = getlogin_r(username, LOGIN_NAME_MAX);
if (result)
{
perror("getlogin_r");
return EXIT_FAILURE;
}
result = printf("Hello %s, you are logged in to %s.\n",
username, hostname);
if (result < 0)
{
perror("printf");
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
Run Code Online (Sandbox Code Playgroud)
可能的输出:
Hello 5gon12eder, you are logged in to example.com.
Run Code Online (Sandbox Code Playgroud)
这似乎比依赖环境变量更安全,而环境变量并不总是存在.
我正在撤回最后一句话,因为
getlogin实际上阻碍了它的使用有利于getenv("LOGIN")和getlogin_r,上述程序中的调用失败,ENOTTY而getenv("USER")在两种情况下都可以运行.关于丹尼斯的回答,请注意getenv("HOSTNAME")对于 Linux可能并不总是有效,因为环境变量可能不会导出到程序。
仅获取计算机名称的多平台 C++ 代码示例(这适用于我的 Win7 和 CentOS 机器):
char *temp = 0;
std::string computerName;
#if defined(WIN32) || defined(_WIN32) || defined(_WIN64)
temp = getenv("COMPUTERNAME");
if (temp != 0) {
computerName = temp;
temp = 0;
}
#else
temp = getenv("HOSTNAME");
if (temp != 0) {
computerName = temp;
temp = 0;
} else {
temp = new char[512];
if (gethostname(temp, 512) == 0) { // success = 0, failure = -1
computerName = temp;
}
delete []temp;
temp = 0;
}
#endif
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
42953 次 |
| 最近记录: |