getpwnam() — Access the user database by user name

Standards

Standards / Extensions C or C++ Dependencies

POSIX.1
XPG4
XPG4.2
Single UNIX Specification, Version 3

both  

Format

#define _POSIX_SOURCE
#include <pwd.h>

struct passwd *getpwnam(const char *name);

General description

Accesses the passwd structure (defined in the pwd.h header file), which contains the following members:
pw_name
User name
pw_uid
User ID (UID) number
pw_gid
Group ID (GID) number
pw_dir
Initial working directory
pw_shell
Initial user program

Returned value

If successful, getpwnam() returns a pointer to a passwd structure containing an entry from the user database with the specified name. Return values may point to the static data that is overwritten on each call.

If unsuccessful, getpwnam() returns a NULL pointer and sets errno to one of the following values:
Error Code
Description
EINVAL
A non-valid user name is detected.

Example

CELEBG16
⁄* CELEBG16
		
   This example provides information for the user data
   base, MEGA.

 *⁄
#define _POSIX_SOURCE
#include <sys⁄types.h>
#include <pwd.h>

main() {
  struct passwd *p;
  char user[]="MEGA";

  if ((p = getpwnam(user)) == NULL)
    perror("getpwnam() error");
  else {
    printf("getpwnam() returned the following info for user %s:\n",
           user);
    printf("  pw_name  : %s\n",       p->pw_name);
    printf("  pw_uid   : %d\n", (int) p->pw_uid);
    printf("  pw_gid   : %d\n", (int) p->pw_gid);
    printf("  pw_dir   : %s\n",       p->pw_dir);
    printf("  pw_shell : %s\n",       p->pw_shell);
  }
}
Output
  pw_name  : MEGA
  pw_uid   : 0
  pw_gid   : 512
  pw_dir   : /u/mega
  pw_shell : /bin/sh

Related information