csymlinkreaddiropendir

Having a dirent that is a symbolic link, how can I get the link-target's path name?


Having opened a directory with opendir() and using readdir() to read out it's entries, I check whether the entry is a symbolic link and if so I'd like to use the name of the target.

(Let's say we have a directory exampledir, in it a file that's a symbolic link called linkfile linking to a directory /path/to/link/target)

Here's a simplified snippet:

#include <sys/types.h> 
#include <dirent.h>
// ...
const char *path_to_dir = "./exampledir"; 
DIR *dir = opendir(path_to_dir); 
dirent *entry = readdir(dir); 
if (entry->d_type == DT_LNK) {
  // find out the link target's name and store / use it, 
  // but how...? 
}

Solution

  • Use the readlink/readlinkat(2) system call.