micro-utils/src/readlink.c

51 lines
856 B
C
Raw Normal View History

2024-07-01 10:23:00 +00:00
#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:
2024-07-03 14:22:50 +00:00
puts("readlink [n] [file1 file2...]\n\t-n Don't add newline");
2024-07-01 10:23:00 +00:00
return 0;
}
}
argv += optind;
argc -= optind;
for (int i = 0; i < argc; i++) {
char path[PATH_MAX + 1];
2024-07-05 16:54:49 +00:00
ssize_t r = readlink(argv[i], path, sizeof(path) - 1);
2024-07-01 10:23:00 +00:00
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;
}
2024-07-05 16:54:49 +00:00
path[r] = '\0';
2024-07-01 10:23:00 +00:00
if (n_flag)
fputs(path, stdout);
else
puts(path);
}
return 0;
}