Tuesday, November 16, 2021

[SOLVED] How to print the current user and system name in Unix?

Issue

Please i am looking forward to learn how to print the current logged-in user and system name in Unix.

#include <unistd.h>
#include <fcntl.h>

using namespace std;

int main(int argc, char **argv)   
{      
     //Print the current logged-in user / username.   
     //Print the name of the system / computer name.

     return 0;
}

I would be grateful if you can provide a line of code or two as demonstration. Thanks


Solution

getuid() gets the id not the username. To get the username you'll have to additionally use getpwuid():

struct passwd *passwd;
passwd = getpwuid ( getuid()); 

printf("The Login Name is %s ", passwd->pw_name);

See it

And for getting the hostname you can use the gethostname() function.



Answered By - codaddict