Use _POSIX_VERSION, not _POSIX_SOURCE.
[gnulib.git] / lib / getugroups.c
1 /* getugroups.c -- return a list of the groups a user is in
2    Copyright (C) 1990, 1991 Free Software Foundation.
3
4    This program is free software; you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation; either version 2, or (at your option)
7    any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program; if not, write to the Free Software
16    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */
17
18 /* Written by David MacKenzie. */
19
20 #include <sys/types.h>
21 #include <grp.h>
22
23 #ifdef HAVE_UNISTD_H
24 #include <unistd.h>
25 #endif
26
27 /* Even though SunOS 4, Ultrix 4, and 386BSD are mostly POSIX.1 compliant,
28    their getgroups system call (except in the `System V' environment, which
29    is troublesome in other ways) fills in an array of int, not gid_t
30    (which is `short' on those systems).  We do the same, for consistency.
31    Kludge, kludge.  */
32
33 #ifdef _POSIX_VERSION
34 #if !defined(sun) && !defined(ultrix) && !defined(__386BSD__)
35 #define GETGROUPS_T gid_t
36 #else /* sun or ultrix or 386BSD */
37 #define GETGROUPS_T int
38 #endif /* sun or ultrix or 386BSD */
39 #else /* not _POSIX_VERSION */
40 #define GETGROUPS_T int
41 #endif /* not _POSIX_VERSION */
42
43 /* setgrent, getgrent, and endgrent are not specified by POSIX.1,
44    so header files might not declare them.
45    If you don't have them at all, we can't implement this function.
46    You lose!  */
47 struct group *getgrent ();
48
49 #if defined(USG) || defined(STDC_HEADERS)
50 #include <string.h>
51 #else
52 #include <strings.h>
53 #endif
54
55 /* Like `getgroups', but for user USERNAME instead of for
56    the current process. */
57
58 int
59 getugroups (maxcount, grouplist, username)
60      int maxcount;
61      GETGROUPS_T *grouplist;
62      char *username;
63 {
64   struct group *grp;
65   register char **cp;
66   register int count = 0;
67
68   setgrent ();
69   while ((grp = getgrent ()) != 0)
70     for (cp = grp->gr_mem; *cp; ++cp)
71       if (!strcmp (username, *cp))
72         {
73           if (maxcount != 0)
74             {
75               if (count >= maxcount)
76                 {
77                   endgrent ();
78                   return count;
79                 }
80               grouplist[count] = grp->gr_gid;
81             }
82           count++;
83         }
84   endgrent ();
85   return count;
86 }