Programming Tips - Linux: pragmatically follow a symlink

Date: 2024sep18 OS: Linux Language: C/C++ Q. Linux: pragmatically follow a symlink A. Use the readlink() function like this
#include <unistd.h> #include <stdio.h> #include <stddef.h> int main() { const char *src = "/htdocs"; char dest[FILENAME_MAX]; const ssize_t size = readlink(src, dest, sizeof(dest)); if (size <= 0) { perror("readlink"); return 1; } // readlink() doesn't add a terminating NUL so we do. // We have checked that size is valid. dest[size] = '\0'; printf("%s links to %s\n", src, dest); }