Getting password file entry for the current user

931 views Asked by At

I have this in my source code:

struct passwd* user_info = getpwnam("root");

Is there anyway to change the "root" and my program will find the current user? For example if I am logged in with user root2 I want info for root2 and not for root.

2

There are 2 answers

3
Staven On BEST ANSWER

You can find the user's uid with getuid() (form unistd.h) and pass it to getpwuid().

3
Shaun07776 On

The following code will get the username in linux,

#include<iostream>
using namespace std;
int main()
{
    std::string name;
    name = system("whoami");
    cout << "Name is : " << name;
    cout << endl;
        return 0;
}