The Linux Programming Interface

(nextflipdebug5) #1
Users and Groups 161

The getpwent() function returns records from the password file one by one, return-
ing NULL when there are no more records (or an error occurs). On the first call,
getpwent() automatically opens the password file. When we have finished with the
file, we call endpwent() to close it.
We can walk through the entire password file printing login names and user
IDs with the following code:


struct passwd *pwd;

while ((pwd = getpwent()) != NULL)
printf("%-8s %5ld\n", pwd->pw_name, (long) pwd->pw_uid);

endpwent();

The endpwent() call is necessary so that any subsequent getpwent() call (perhaps in
some other part of our program or in some library function that we call) will
reopen the password file and start from the beginning. On the other hand, if we
are part-way through the file, we can use the setpwent() function to restart from the
beginning.
The getgrent(), setgrent(), and endgrent() functions perform analogous tasks for
the group file. We omit the prototypes for these functions because they are similar
to those of the password file functions described above; see the manual pages for
details.


Retrieving records from the shadow password file


The following functions are used to retrieve individual records from the shadow
password file and to scan all records in that file.


#include <pwd.h>

struct passwd *getpwent(void);
Returns pointer on success, or NULL on end of stream or error
void setpwent(void);
void endpwent(void);

#include <shadow.h>

struct spwd *getspnam(const char *name);
Returns pointer on success, or NULL on not found or error
struct spwd *getspent(void);
Returns pointer on success, or NULL on end of stream or error
void setspent(void);
void endspent(void);
Free download pdf