Managing users on a Linux system is a fundamental task for system administrators and developers. Retrieving a complete list of users programmatically is a common requirement. This tutorial explains how to get a list of users on Linux using C++.
The provided code loops through all entries in the password file (/etc/passwd
on Unix-like systems) using the getpwent
function to retrieve each entry's information. It prints out the username of each entry to the standard output, and then it closes the password file using endpwent
.
#include <pwd.h>
#include <iostream>
int main()
{
passwd *entry;
while ((entry = getpwent()) != nullptr) {
std::cout << entry->pw_name << std::endl;
}
endpwent();
return 0;
}
Leave a Comment
Cancel reply