chown.c 1.1 KB

1234567891011121314151617181920212223242526272829303132333435
  1. /* SPDX-License-Identifier: BSD-3-Clause */
  2. /*
  3. * Copyright (C) 2022, 2023 Ferass El Hafidi <vitali64pmemail@protonmail.com>
  4. */
  5. #include <errno.h>
  6. #include <unistd.h>
  7. #include <stdio.h>
  8. #include <pwd.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #define REQ_PRINT_USAGE /* Require print_usage() from ../common/common.h */
  12. #define REQ_ERRPRINT /* Require errprint() from ../common/common.h */
  13. #define DESCRIPTION "Change file ownership."
  14. #define OPERANDS "owner file"
  15. #include "../common/common.h"
  16. int main(int argc, char *const argv[]) {
  17. struct passwd *user;
  18. if (argc == 1) {
  19. print_usage(argv[0], DESCRIPTION, OPERANDS, VERSION);
  20. return 1;
  21. }
  22. if ((user = getpwnam(argv[1])) == NULL && (user = getpwuid(strtol(argv[1], NULL, 10))) == NULL)
  23. return errprint(argv[0], argv[1], errno); /* User doesn't exist */
  24. /* User found! */
  25. else if ((user = getpwnam(argv[1])) != NULL)
  26. chown(argv[2], user->pw_uid, user->pw_gid);
  27. else if ((user = getpwuid(strtol(argv[1], NULL, 10))) != NULL)
  28. chown(argv[2], user->pw_uid, user->pw_gid);
  29. if (errno) return errprint(argv[0], argv[2], errno);
  30. return 0;
  31. }