title: How to print groups of all local users?
body: <p>I want to print all groups of users stored in /etc/passwd. Seems easy enough, I can just use getpwent() and getgrouplist(). I came with this code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;pwd.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;grp.h&gt;
  
  int main(int argc, char** argv){
  
      struct passwd* user;
      int nGroups = 20;
      gid_t* groups;
      groups = malloc(nGroups * sizeof(gid_t));
      struct group* gr;
      while(user = getpwent()){
          printf("%s : ", user-&gt;pw_name);
          getgrouplist(user-&gt;pw_name, user-&gt;pw_gid, groups, &amp;nGroups);
          int i;
          for(i = 0; i &lt; nGroups; ++i){
              gr = getgrgid(groups[i]);
              if(gr){
                  printf("%s ", gr-&gt;gr_name);
              }  
          }
          printf("\n");
      }
  
      free(groups);
      return 0;
  }
  </code></pre>
  
  <p>It gives me this output:</p>
  
  <pre><code>root : root 
  daemon : daemon 
  bin : bin 
  .
  .
  .
  pulse : pulse root 
  ricenwind : ricenwind adm root root root root root root 
  vboxadd : daemon 
  </code></pre>
  
  <p>which is clearly wrong, as for example using</p>
  
  <pre><code>groups ricenwind
  </code></pre>
  
  <p>gives me:</p>
  
  <pre><code>ricenwind : ricenwind adm cdrom sudo dip plugdev lpadmin sambashare
  </code></pre>