Monday, January 2, 2012

How to list all users / groups programmatically (Linux)

In my previous post I described how to list all users / groups on Windows machine.

This post describes how to list all users / groups of Linux server.

Use functions  getpwent for users and  getgrent() for groups (type man getpwent or man getgreent for details).

The sample code looks like:

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

void list_users(void) {
  struct passwd *p = getpwent();

  for (; p; p = getpwent()) {
    puts(p->pw_name);
  }

  endpwent();
}

void list_groups(void) {
  struct group *p = getgrent();

  for (; p; p = getgrent()) {
    puts(p->gr_name);
  }

  endgrent();
}

No comments:

Post a Comment