Skip to content

Instantly share code, notes, and snippets.

@migerh
Created December 29, 2013 23:29
Show Gist options
  • Save migerh/8175984 to your computer and use it in GitHub Desktop.
Save migerh/8175984 to your computer and use it in GitHub Desktop.
List all groups the current user is member of.
#include <stdio.h>
#include <unistd.h>
#include <grp.h>
#include <stdlib.h>
#include <malloc.h>
int main()
{
struct group *gr;
int i, n;
gid_t *groups;
n = getgroups(0, NULL);
if (n < 0) {
fprintf(stderr, "Unable to retrieve groups: %m\n");
return EXIT_FAILURE;
}
groups = malloc(n * sizeof(gid_t));
if (!groups)
return EXIT_FAILURE;
if (getgroups(n, groups) < 0) {
fprintf(stderr, "Unable to retrieve groups: %m\n");
free(groups);
return EXIT_FAILURE;
}
printf("Found %d groups:\n", n);
for (i = 0; i < n; i++) {
gr = getgrgid(groups[i]);
printf(" * %s\n", gr->gr_name);
}
free(groups);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment