getpwent_r - Linux
Overview
getpwent_r is a C library function that retrieves the next password entry from the system password file /etc/passwd
. It is typically used to iterate through all user accounts on the system.
Syntax
int getpwent_r(struct passwd *result, struct passwd *buffer, char *buf, size_t bufsize, struct passwd **resultp);
Options/Flags
None
Examples
Simple example
#include <pwd.h>
int main() {
struct passwd *pw;
while ((pw = getpwent_r())) {
printf("Username: %s, UID: %d\n", pw->pw_name, pw->pw_uid);
}
endpwent();
return 0;
}
Complex example
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
struct passwd *pw;
struct passwd *pw_result;
char buffer[512];
while ((pw = getpwent_r(pw_result, buffer, sizeof(buffer), &pw_result))) {
printf("Username: %s, UID: %d\n", pw->pw_name, pw->pw_uid);
}
endpwent();
return 0;
}
Common Issues
- Result buffer too small: If the buffer passed to
getpwent_r
is too small to hold the next password entry, the function will returnNULL
and seterrno
toERANGE
. - Password file not accessible: If the system password file
/etc/passwd
is not accessible,getpwent_r
will returnNULL
and seterrno
toEACCES
.
Integration
getpwent_r can be combined with other Linux commands and tools to gather information about user accounts. For example:
getpwent_r | grep "username"
This command will print information about users whose username matches "username".
Related Commands
- getpwuid_r: Get password entry by user ID
- getpwnam_r: Get password entry by username