How to get the username in C/C++ in Linux?

#include <iostream>
#include <unistd.h>
int main()
{
    std::string Username = getlogin();
    std::cout << Username << std::endl;
    return 0 ;
}

Another way is this -

#include <iostream>
using namespace std;
int main()
{
       cout << system("whoami");
}

The function getlogin_r() defined in unistd.h returns the username. See man getlogin_r for more information.

Its signature is:

int getlogin_r(char *buf, size_t bufsize);

Needless to say, this function can just as easily be called in C or C++.


From http://www.unix.com/programming/21041-getting-username-c-program-unix.html :

/* whoami.c */
#define _PROGRAM_NAME "whoami"
#include <stdlib.h>
#include <pwd.h>
#include <stdio.h>

int main(int argc, char *argv[])
{
  register struct passwd *pw;
  register uid_t uid;
  int c;

  uid = geteuid ();
  pw = getpwuid (uid);
  if (pw)
    {
      puts (pw->pw_name);
      exit (EXIT_SUCCESS);
    }
  fprintf (stderr,"%s: cannot find username for UID %u\n",
       _PROGRAM_NAME, (unsigned) uid);
  exit (EXIT_FAILURE);

}

Just take main lines and encapsulate it in class:

class Env{
    public:
    static std::string getUserName()
    {
        uid_t uid = geteuid ();
        struct passwd *pw = getpwuid (uid);
        if (pw)
        {
            return std::string(pw->pw_name);
        }
        return {};
    }
};

For C only:

const char *getUserName()
{
  uid_t uid = geteuid();
  struct passwd *pw = getpwuid(uid);
  if (pw)
  {
    return pw->pw_name;
  }

  return "";
}

Tags:

Linux

C++

C

Posix