如何获取一个符号链接的绝对路径?
我怎样才能得到一个符号链接的绝对路径?如果我这样做以下列方式:
How can I get the absolute path of a symbolic link? If I do it in the following way:
char buf[100];
realpath(symlink, buf);
我不会符号链接的绝对路径,而是我会得到的绝对路径这个符号链接的链接。现在的问题是:如果我想要得到的符号链接本身的腹肌路径?是否有在Linux中的 C 的任何功能,可以让我这样做?
注:我想实现的是符号链接本身的绝对路径。不是它所指向的路径!例如,一个smybolic链接的相对路径为:任务2 / sym_lnk
,我想它的ABS路径,它可以是:
I won't get the absolute path of the symlink, but instead I would get the absolute path this symlink links to. Now my question is: What If I want to get the abs path of the symlink itself? Is there any function in Linux c that allows me to do so?
Note: What I'd like to achieve is the absolute path of the symbolic link itself. Not the path it's pointing to! e.g the relative path of a smybolic link is: Task2/sym_lnk
, I want its abs path, which can be: home/user/kp/Task2/sym_lnk
您可以使用真实路径()函数符号链接的父文件夹,然后您连接符号链接名称。
You can use realpath() function with the parent folder of the symlink, then you concatenate the symlink name.
#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's 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;
}
如果你使用上面code。与目录,它需要一个特殊情况。和..,但与./和../\"
If you use the above code with directories, it needs an special case for "." and "..", but works with "./" and "../"