0

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.

Mat
  • 202,337
  • 40
  • 393
  • 406
BlackM
  • 3,927
  • 8
  • 39
  • 69

2 Answers2

1

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

Staven
  • 3,113
  • 16
  • 20
  • 1
    "it's not working!" is not useful. What exactly is not working? How exactly did you write the code? – Mat Jan 22 '12 at 14:36
  • struct passwd* user_info = getpwnam(getuid()); – BlackM Jan 22 '12 at 14:42
  • 2
    @user776720: please re-read that answer, and the man page. `getpwnam` takes a string, `getuid` returns an uid which is not a string. The answer provides the right function to use with `getuid`. – Mat Jan 22 '12 at 14:48
-1

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;
}
Shaun07776
  • 1,052
  • 1
  • 10
  • 16
  • 3
    `system()` returns the command's exit status, not it's standard output. – Staven Jan 22 '12 at 14:22
  • 1
    And you're not including the header for `system`, even if it somehow worked like that. – Mat Jan 22 '12 at 14:25
  • Also, this depends on the user having the `whoami` program somewhere in their path. –  Mar 17 '13 at 12:08