logo

utils-std

Collection of commonly available Unix tools

readlink.c (1327B)


  1. // utils-std: Collection of commonly available Unix tools
  2. // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
  3. // SPDX-License-Identifier: MPL-2.0
  4. #define _POSIX_C_SOURCE 200809L
  5. #include <errno.h>
  6. #include <limits.h> // PATH_MAX
  7. #include <stdbool.h>
  8. #include <stdio.h> // fprintf
  9. #include <string.h> // strerror
  10. #include <unistd.h> // getopt
  11. static void
  12. usage()
  13. {
  14. fprintf(stderr, "Usage: readlink [-n] file\n");
  15. }
  16. int
  17. main(int argc, char *argv[])
  18. {
  19. bool newline = true;
  20. int c = -1;
  21. while((c = getopt(argc, argv, ":n")) != -1)
  22. {
  23. switch(c)
  24. {
  25. case 'n':
  26. newline = false;
  27. break;
  28. case ':':
  29. fprintf(stderr, "readlink: Error: Missing operand for option: '-%c'\n", optopt);
  30. usage();
  31. return 1;
  32. case '?':
  33. fprintf(stderr, "readlink: Error: Unrecognised option: '-%c'\n", optopt);
  34. usage();
  35. return 1;
  36. }
  37. }
  38. argv += optind;
  39. argc -= optind;
  40. if(argc != 1)
  41. {
  42. fprintf(stderr, "readlink: Expected one file as argument, got %d\n", argc);
  43. usage();
  44. return 1;
  45. }
  46. char buf[PATH_MAX] = "";
  47. if(readlink(argv[0], buf, sizeof(buf) - 1) < 0)
  48. {
  49. fprintf(stderr,
  50. "readlink: Error: Failed reading symbolic link of '%s': %s\n",
  51. argv[0],
  52. strerror(errno));
  53. return 1;
  54. }
  55. printf("%s", buf);
  56. if(newline) printf("\n");
  57. return 0;
  58. }