4

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

2
  • 1
    Is this a home work question? You should probably do some research rather than ask something like this straight out. See en.wikipedia.org/wiki/Exec_(operating_system) for instance. Commented Jan 4, 2012 at 8:29
  • okay.. thanks. [between, it is not a homework]. Commented Jan 4, 2012 at 8:31

3 Answers 3

5

User --> getuid() (see also geteuid()).

Machine name --> gethostname().

That is pure C. I don't know whether C++ has other library calls for that.

Sign up to request clarification or add additional context in comments.

1 Comment

I wouldn't call it "pure C". The functions are defined by POSIX, not by the C standard, and they might not be available on some systems (Windows, for example). (Yes, I know the question is tagged "unix".)
4

You need to call the uname, gethostname, getuid (and perhaps getgid) system calls, and to convert the numerical uid with getpwent function.

Comments

3

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.