Obtención de ruta absoluta de un archivo
-
04-07-2019 - |
Pregunta
¿Cómo puedo convertir una ruta relativa en una ruta absoluta en C en Unix? ¿Existe una función de sistema conveniente para esto?
En Windows hay una función GetFullPathName
que hace el trabajo, pero no encontré algo similar en Unix ...
Solución
Utilice realpath () .
La función
realpath ()
se derivará, de la ruta señalada porfile_name
, una ruta de acceso absoluta que Nombra el mismo archivo, cuya resolución no implica '.
', '..
', o enlaces simbólicos. La ruta de acceso generada se almacenará como un nulo terminado cadena, hasta un máximo de{PATH_MAX}
bytes, en el buffer apuntado porresolver_name
.Si
resolver_name
es un puntero nulo, el comportamiento derealpath ()
es definida por la implementación.
El siguiente ejemplo genera un ruta de acceso absoluta para el archivo identificado por el symlinkpath argumento. La ruta de acceso generada es almacenado en la matriz de ruta real.
#include <stdlib.h>
...
char *symlinkpath = "/tmp/symlink/file";
char actualpath [PATH_MAX+1];
char *ptr;
ptr = realpath(symlinkpath, actualpath);
Otros consejos
Pruebe realpath ()
en stdlib.h
char filename[] = "../../../../data/000000.jpg";
char* path = realpath(filename, NULL);
if(path == NULL){
printf("cannot find file with name[%s]\n", filename);
} else{
printf("path[%s]\n", path);
free(path);
}
También intente " getcwd "
#include <unistd.h>
char cwd[100000];
getcwd(cwd, sizeof(cwd));
std::cout << "Absolute path: "<< cwd << "/" << __FILE__ << std::endl;
Resultado:
Absolute path: /media/setivolkylany/WorkDisk/Programming/Sources/MichailFlenov/main.cpp
Entorno de prueba:
setivolkylany@localhost$/ lsb_release -a
No LSB modules are available.
Distributor ID: Debian
Description: Debian GNU/Linux 8.6 (jessie)
Release: 8.6
Codename: jessie
setivolkylany@localhost$/ uname -a
Linux localhost 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u2 (2016-10-19) x86_64 GNU/Linux
setivolkylany@localhost$/ g++ --version
g++ (Debian 4.9.2-10) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
También hay una pequeña biblioteca de ruta cwalk que funciona en varias plataformas. Tiene cwk_path_get_absolute para hacer eso:
#include <cwalk.h>
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
char buffer[FILENAME_MAX];
cwk_path_get_absolute("/hello/there", "./world", buffer, sizeof(buffer));
printf("The absolute path is: %s", buffer);
return EXIT_SUCCESS;
}
Salidas:
The absolute path is: /hello/there/world