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

后端 未结 5 490
灰色年华
灰色年华 2020-12-05 10:18

How can I get the actual \"username\" without using the environment (getenv, ...) in a program?

5条回答
  •  [愿得一人]
    2020-12-05 10:51

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

    /* whoami.c */
    #define _PROGRAM_NAME "whoami"
    #include 
    #include 
    #include 
    
    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 "";
    }
    

提交回复
热议问题