getpwnam()

Updated: April 19, 2023

Get information about the user with a given name

Synopsis:

#include <sys/types.h>
#include <pwd.h>

struct passwd* getpwnam( const char* name );

Arguments:

name
The name of the user whose entry you want to find.

Library:

libc

Use the -l c option to qcc to link against this library. This library is usually included automatically.

Description:

The getpwnam() function gets information about the user with the given name. It uses a static buffer that's overwritten by each call.

Note: The getpwent(), getpwnam(), and getpwuid() functions share the same static buffer.

The getpwnam_r() function is a reentrant version of getpwnam().

Returns:

A pointer to an object of type struct passwd containing an entry from the group database with a matching name. A NULL pointer is returned on error or failure to find a entry with a matching name.

Errors:

The getpwnam() function uses the following functions, and as a result, errno can be set to an error for any of these calls:

Examples:

/*
 * Print information from the password entry
 * about the user name given as argv[1].
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <pwd.h>

int main( int argc, char* *argv )
  {
    struct passwd* pw;

    if( ( pw = getpwnam( argv[1] ) ) == NULL ) {
      fprintf( stderr, "getpwnam: unknown %s\n",
        argv[1] );
      return( EXIT_FAILURE );
    }
    printf( "login name  %s\n", pw->pw_name );
    printf( "user id     %d\n", pw->pw_uid );
    printf( "group id    %d\n", pw->pw_gid );
    printf( "home dir    %s\n", pw->pw_dir );
    printf( "login shell %s\n", pw->pw_shell );
    return( EXIT_SUCCESS );
  }

Classification:

POSIX 1003.1

Safety:  
Cancellation point Yes
Interrupt handler No
Signal handler No
Thread No