How to get the absolute path to a symbolic link?

How can I get the absolute path of a symbolic link? If I do it as follows:

char buf[100]; realpath(symlink, buf); 

I will not get the absolute path for the symbolic link, but instead I will get the absolute path referenced by the symbolic links. Now my question is: what if I want to get the paragraph path of the symbolic link itself? Is there any function in Linux c that allows me to do this? Note. What I would like to achieve is the absolute path of the symbolic link itself. Not the way he points to! for example, the relative path of smybolic link: Task2/sym_lnk , I want its paragraph path, which can be: home/user/kp/Task2/sym_lnk

+5
source share
2 answers

You can use the realpath () function with the parent folder of the symlink, then you merge the name of the symlink.

 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include <unistd.h> // Find the last occurrence of c in str, otherwise returns NULL char* find_last_of( char *str, char c ) { for( char *i = str + strlen(str) ; i >= str ; i-- ) if( *i == c ) return i; return NULL; } // Does the job char* getAbsPath( char *path ) { char *name; // Stores the symlink name char *tmp; // Aux for store the last / char *absPath = malloc( PATH_MAX ); // Stores the absolute path tmp = find_last_of( path, '/' ); // If path is only the symlink name (there no /), then the // parent folder is the current work directory if( tmp == NULL ){ name = strdup( path ); getcwd( absPath, PATH_MAX ); // Is already absolute path } else{ // Extract the name and erase it from the original // path. name = strdup( tmp + 1 ); *tmp = '\0'; // Get the real path of the parent folder. realpath( path, absPath ); } // Concatenate the realpath of the parent and "/name" strcat( absPath, "/" ); strcat( absPath, name ); free( name ); return absPath; } // Test the function int main( int argc, char **argv ) { char *absPath; if( argc != 2 ){ fprintf( stderr, "Use:\n\n %s <symlink>\n", *argv ); return -1; } // Verify if path exists if( access( argv[1], F_OK ) ){ perror( argv[1] ); return -1; } absPath = getAbsPath( argv[1] ); printf( "Absolute Path: %s\n", absPath ); free( absPath ); return 0; } 

If you use the above code with directories, it needs a special case for "." and "..", but works with "./" and "../"

+2
source

You can use the readlink() system call

 readlink(const char* fdpath,char* filepath, 256); 

fdpath is the path symbol of a symbolic link. Something like /proc/pid/fd/link_number

filepath is the file path pointing to

+1
source

Source: https://habr.com/ru/post/1235094/


All Articles