ln.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /* SPDX-License-Identifier: BSD-3-Clause */
  2. /*
  3. * Copyright (C) 2022, 2023 Ferass El Hafidi <vitali64pmemail@protonmail.com>
  4. */
  5. #include <unistd.h>
  6. #include <stdio.h>
  7. #include <errno.h>
  8. #include <string.h>
  9. #define REQ_PRINT_USAGE /* Require print_usage() from ../common/common.h */
  10. #define REQ_ERRPRINT /* Require errprint() from ../common/common.h */
  11. #define DESCRIPTION "Link files."
  12. #define OPERANDS "[-fs] [-P|-L] source_file target_file"
  13. #include "../common/common.h"
  14. int getopt(int argc, char *const argv[], const char *optstring);
  15. int main(int argc, char *const argv[]) {
  16. int argument;
  17. char param[256], *buffer = NULL, *argv0 = strdup(argv[0]);
  18. if (argc != 3) {
  19. print_usage(argv[0], DESCRIPTION, OPERANDS, VERSION);
  20. return 1;
  21. }
  22. while ((argument = getopt(argc, argv, "fsPL")) != -1) {
  23. if (argument == '?') {
  24. print_usage(argv[0], DESCRIPTION, OPERANDS, VERSION);
  25. return 1;
  26. }
  27. param[argument] = argument;
  28. } argc -= optind; argv += optind;
  29. if (param['f']) remove(argv[1]);
  30. if (errno && errno != ENOENT) return errprint(argv0, argv[0], errno);
  31. errno = 0; /* Not reached if errno == ENOENT (no such file) */
  32. if (param['s']) symlink(argv[0], argv[1]);
  33. /* The -P option is the default behavior (at least on musl),
  34. * so no if statement.
  35. */
  36. else if (param['L']) {
  37. readlink(argv[0], buffer, strlen(buffer)); /* Read the link */
  38. if (errno) return errprint(argv0, argv[0], errno);
  39. link(buffer, argv[1]);
  40. }
  41. else link(argv[0], argv[1]);
  42. return errprint(argv0, argv[1], errno);
  43. }