I'm developing an application and in one of its methods I need to capture the name of the computer and the user logged in to the machine, then display the screen for the user. What is the best way to do this?
I'm developing an application and in one of its methods I need to capture the name of the computer and the user logged in to the machine, then display the screen for the user. What is the best way to do this?
In Windows environment you can use getenv("COMPUTERNAME")
, getenv("USER")
.
In Linux - getenv("HOSTNAME")
, getenv("USER")
.
See also reference getenv
.
Complementing the above answer,
getenv()
returns:
C String
sets the environment variable that stores the user name to $ USER, so to use the function in linux
to get the current user name,
make linux
.
getenv("USER")
does not have a "USER" environment variable but rather, "USERNAME", which returns the same thing (the username), so to use the function in windows
, make windows
.
You can type "set" in a console / terminal / prompt window and see all environment variables currently configured in getenv("USERNAME")
. There you should find "USERNAME" instead of "USER".
In%%, if you type "env" in the terminal, you will see that there is a "USER" variable, saving the current user name.
windows
is set to linux
Example:
#include <iostream>
#include <cstdlib>
int main(){
/*Para obter o nome de usuário no linux*/
#ifdef __linux__
std::cout << "O nome do usuário atual é: " << getenv("USER") << std::endl;
#endif
/*Para obter o nome de usuário no windows*/
#ifdef _WIN32
std::cout << "O nome do usuário atual é: " << getenv("USERNAME") << std::endl;
#endif
}