gtpc2m3yC/C++ Language Support User's Guide

getpwnam-Access the User Database by Name

This function gets information about the user with the specified name.

Format

#include <pwd.h>
struct passwd *getpwnam(char const *name)

name
A pointer of type character to a string name (NULL-terminated) representing the name of the user ID (UID) to be retrieved from file. name must be lowercase.

Normal Return

If successful, the getpwnam function returns a pointer to struct passwd with an entry from the user database for the specified name.

The return value is a pointer to static data that is overwritten by each call.

struct passwd, defined in the pwd.h C header file, contains the following members:

pw_name
Pointer to the password user name character string.

pw_uid
The numeric UID.

pw_gid
The numeric group ID (GID).

pw_gecos
Pointer to the comment character string.

pw_dir
Pointer to the initial working directory character string.

pw_shell
Pointer to the character string name of the initial shell (user program).

Error Return

If unsuccessful, the getpwnam function returns a NULL pointer and sets errno to the appropriate value, as follows:

EINVAL
Indicates that the length of the name parameter is incorrect. The length of name must be equal to the length of the user name in the password user ID file; it must also be less than 256 characters.

EIO
An input/output (I/O) error occurred.

EMFILE
The process has already reached its maximum number of open file descriptors. This limit is given by OPEN_MAX, which is defined in the limits.h header file.

ENFILE
The TPF system has already reached its maximum number of open files.

Programming Considerations

Examples

The following example provides information for user name tpfuser1.

#include <pwd.h>
#include <stdio.h>
 
int main(void) {
 
char prthdr[] =
             "getpwnam() returned the following info for your user id:"
struct passwd *p;
char user[] = "tpfuser1";
    if ( ( p = getpwnam ( user ) ) == NULL )
     perror ( "getpwnam() error" );
     else {
       printf( "%s\n", prthdr );
       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);
       }
    return 0;
}

The getpwnam function returns the following information for the user ID of the calling function.

getpwnam() returned the following info for your user id:
pwname   :  tpfuser1
pw_uid   :  260
pw_gid   :  100
pw_dir   :  /usr
pw_shell :

Related Information

getpwuid-Access the User Database by User ID.