Question

Comment puis-je convertir un chemin relatif en un chemin absolu en C sous Unix? Existe-t-il une fonction système pratique pour cela?

Sous Windows, il existe une fonction GetFullPathName qui fait le travail, mais je n'ai pas trouvé quelque chose de similaire sous Unix ...

Était-ce utile?

La solution

Utilisez realpath () .

  

La fonction realpath () doit dériver,   du chemin indiqué par    nom_fichier , un chemin absolu qui   nomme le même fichier, dont la résolution   n'implique pas '. ', ' .. ' ou   liens symboliques. Le chemin généré   doit être stocké comme un null-terminé   chaîne, jusqu'à un maximum de {PATH_MAX}   octets, dans le tampon pointé par    nom_résolu .

     

Si nom_résolu est un pointeur nul,   le comportement de realpath () est   défini par la mise en œuvre.

  

L'exemple suivant génère un   chemin absolu du fichier   identifié par le symlinkpath   argument. Le chemin généré est   stocké dans le tableau actualpath.

#include <stdlib.h>
...
char *symlinkpath = "/tmp/symlink/file";
char actualpath [PATH_MAX+1];
char *ptr;


ptr = realpath(symlinkpath, actualpath);

Autres conseils

Essayez realpath () dans 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);
}

Essayez également "getcwd"

#include <unistd.h>

char cwd[100000];
getcwd(cwd, sizeof(cwd));
std::cout << "Absolute path: "<< cwd << "/" << __FILE__ << std::endl;

Résultat:

Absolute path: /media/setivolkylany/WorkDisk/Programming/Sources/MichailFlenov/main.cpp

Environnement de 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.

Il existe également une petite bibliothèque de chemins cwalk qui fonctionne sur plusieurs plates-formes. Il a cwk_path_get_absolute pour le faire:

#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;
}

Sorties:

The absolute path is: /hello/there/world
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top