readlink.c (1327B)
- // utils-std: Collection of commonly available Unix tools
- // SPDX-FileCopyrightText: 2017 Haelwenn (lanodan) Monnier <contact+utils@hacktivis.me>
- // SPDX-License-Identifier: MPL-2.0
- #define _POSIX_C_SOURCE 200809L
- #include <errno.h>
- #include <limits.h> // PATH_MAX
- #include <stdbool.h>
- #include <stdio.h> // fprintf
- #include <string.h> // strerror
- #include <unistd.h> // getopt
- static void
- usage()
- {
- fprintf(stderr, "Usage: readlink [-n] file\n");
- }
- int
- main(int argc, char *argv[])
- {
- bool newline = true;
- int c = -1;
- while((c = getopt(argc, argv, ":n")) != -1)
- {
- switch(c)
- {
- case 'n':
- newline = false;
- break;
- case ':':
- fprintf(stderr, "readlink: Error: Missing operand for option: '-%c'\n", optopt);
- usage();
- return 1;
- case '?':
- fprintf(stderr, "readlink: Error: Unrecognised option: '-%c'\n", optopt);
- usage();
- return 1;
- }
- }
- argv += optind;
- argc -= optind;
- if(argc != 1)
- {
- fprintf(stderr, "readlink: Expected one file as argument, got %d\n", argc);
- usage();
- return 1;
- }
- char buf[PATH_MAX] = "";
- if(readlink(argv[0], buf, sizeof(buf) - 1) < 0)
- {
- fprintf(stderr,
- "readlink: Error: Failed reading symbolic link of '%s': %s\n",
- argv[0],
- strerror(errno));
- return 1;
- }
- printf("%s", buf);
- if(newline) printf("\n");
- return 0;
- }