db.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /* User and Group Database Example
  2. Copyright (C) 1991-2019 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU General Public License
  5. as published by the Free Software Foundation; either version 2
  6. of the License, or (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program; if not, see <http://www.gnu.org/licenses/>.
  13. */
  14. #include <grp.h>
  15. #include <pwd.h>
  16. #include <sys/types.h>
  17. #include <unistd.h>
  18. #include <stdlib.h>
  19. int
  20. main (void)
  21. {
  22. uid_t me;
  23. struct passwd *my_passwd;
  24. struct group *my_group;
  25. char **members;
  26. /* Get information about the user ID. */
  27. me = getuid ();
  28. my_passwd = getpwuid (me);
  29. if (!my_passwd)
  30. {
  31. printf ("Couldn't find out about user %d.\n", (int) me);
  32. exit (EXIT_FAILURE);
  33. }
  34. /* Print the information. */
  35. printf ("I am %s.\n", my_passwd->pw_gecos);
  36. printf ("My login name is %s.\n", my_passwd->pw_name);
  37. printf ("My uid is %d.\n", (int) (my_passwd->pw_uid));
  38. printf ("My home directory is %s.\n", my_passwd->pw_dir);
  39. printf ("My default shell is %s.\n", my_passwd->pw_shell);
  40. /* Get information about the default group ID. */
  41. my_group = getgrgid (my_passwd->pw_gid);
  42. if (!my_group)
  43. {
  44. printf ("Couldn't find out about group %d.\n",
  45. (int) my_passwd->pw_gid);
  46. exit (EXIT_FAILURE);
  47. }
  48. /* Print the information. */
  49. printf ("My default group is %s (%d).\n",
  50. my_group->gr_name, (int) (my_passwd->pw_gid));
  51. printf ("The members of this group are:\n");
  52. members = my_group->gr_mem;
  53. while (*members)
  54. {
  55. printf (" %s\n", *(members));
  56. members++;
  57. }
  58. return EXIT_SUCCESS;
  59. }