micro-utils/src/readlink.c
2024-07-09 11:02:46 +03:00

51 lines
856 B
C

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <limits.h>
#include <errno.h>
int main(int argc, char **argv) {
char n_flag = 0;
int opt;
while ((opt = getopt(argc, argv, "n")) != -1) {
switch (opt) {
case 'n':
n_flag = 1;
break;
default:
puts("readlink [n] [file1 file2...]\n\t-n Don't add newline");
return 0;
}
}
argv += optind;
argc -= optind;
for (int i = 0; i < argc; i++) {
char path[PATH_MAX + 1];
ssize_t r = readlink(argv[i], path, sizeof(path) - 1);
if (r < 0) {
fprintf(stderr, "readlink: %s: %s\n", argv[i], strerror(errno));
return 1;
}
if (r > (ssize_t)sizeof(path)) {
fprintf(stderr, "readlink: %s: path too long\n", argv[i]);
return 1;
}
path[r] = '\0';
if (n_flag)
fputs(path, stdout);
else
puts(path);
}
return 0;
}