如何获取符号链接的绝对路径?如果我按照以下方式进行:
char buf[100];
realpath(symlink, buf);
我不会获得符号链接的绝对路径,但我会获得此符号链接链接到的绝对路径。现在我的问题是:如果我想获取符号链接本身的绝对路径怎么办? Linux C 中有什么函数可以让我这样做吗?
注意:我想要实现的是符号链接本身的绝对路径,而不是它指向的路径!例如,如果符号链接的相对路径是Task2/sym_lnk
,我想要它的绝对路径,可以是/home/user/kp/Task2/sym_lnk
.
您可以将 realpath() 函数与符号链接的父文件夹一起使用,然后连接符号链接名称。
#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;
}
如果将上述代码与目录一起使用,则需要“.”的特殊情况。和“..”,但适用于“./”和“../”
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)