Ottenere il percorso assoluto di un file
-
04-07-2019 - |
Domanda
Come posso convertire un percorso relativo in un percorso assoluto in C su Unix? Esiste una comoda funzione di sistema per questo?
Su Windows esiste una funzione GetFullPathName
che svolge il compito, ma non ho trovato qualcosa di simile su Unix ...
Soluzione
Usa realpath () .
La funzione
realpath ()
deve derivare, dal percorso indicato danome_file
, un percorso assoluto che nomina lo stesso file, la cui risoluzione non implica '.
', '..
' o collegamenti simbolici. Il percorso generato deve essere archiviato come null-terminated stringa, fino a un massimo di{PATH_MAX}
byte, nel buffer indicato daresolved_name
.Se
resolved_name
è un puntatore null, il comportamento direalpath ()
è implementazione definita.
Il seguente esempio genera un percorso assoluto per il file identificato dal symlinkpath discussione. Il percorso generato è memorizzato nell'array actualpath.
#include <stdlib.h>
...
char *symlinkpath = "/tmp/symlink/file";
char actualpath [PATH_MAX+1];
char *ptr;
ptr = realpath(symlinkpath, actualpath);
Altri suggerimenti
Prova realpath ()
in 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);
}
Prova anche " getcwd "
#include <unistd.h>
char cwd[100000];
getcwd(cwd, sizeof(cwd));
std::cout << "Absolute path: "<< cwd << "/" << __FILE__ << std::endl;
Risultato:
Absolute path: /media/setivolkylany/WorkDisk/Programming/Sources/MichailFlenov/main.cpp
Ambiente di test:
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.
Esiste anche una piccola libreria di percorsi cwalk che funziona su più piattaforme. Ha cwk_path_get_absolute per farlo:
#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;
}
Uscite:
The absolute path is: /hello/there/world