db.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. /* User and Group Database Example
  2. Copyright (C) 1991-2026 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 <https://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. #include <stdio.h>
  20. int
  21. main (void)
  22. {
  23. uid_t me;
  24. struct passwd *my_passwd;
  25. struct group *my_group;
  26. char **members;
  27. /* Get information about the user ID. */
  28. me = getuid ();
  29. my_passwd = getpwuid (me);
  30. if (!my_passwd)
  31. {
  32. printf ("Couldn't find out about user %d.\n", (int) me);
  33. exit (EXIT_FAILURE);
  34. }
  35. /* Print the information. */
  36. printf ("I am %s.\n", my_passwd->pw_gecos);
  37. printf ("My login name is %s.\n", my_passwd->pw_name);
  38. printf ("My uid is %d.\n", (int) (my_passwd->pw_uid));
  39. printf ("My home directory is %s.\n", my_passwd->pw_dir);
  40. printf ("My default shell is %s.\n", my_passwd->pw_shell);
  41. /* Get information about the default group ID. */
  42. my_group = getgrgid (my_passwd->pw_gid);
  43. if (!my_group)
  44. {
  45. printf ("Couldn't find out about group %d.\n",
  46. (int) my_passwd->pw_gid);
  47. exit (EXIT_FAILURE);
  48. }
  49. /* Print the information. */
  50. printf ("My default group is %s (%d).\n",
  51. my_group->gr_name, (int) (my_passwd->pw_gid));
  52. printf ("The members of this group are:\n");
  53. members = my_group->gr_mem;
  54. while (*members)
  55. {
  56. printf (" %s\n", *(members));
  57. members++;
  58. }
  59. return EXIT_SUCCESS;
  60. }