문제

UNIX의 C의 절대 경로로 상대 경로를 어떻게 변환 할 수 있습니까? 이것에 대한 편리한 시스템 기능이 있습니까?

창문에는 a가 있습니다 GetFullPathName 작업을 수행하는 기능이지만 유닉스에서 비슷한 것을 찾지 못했습니다 ...

도움이 되었습니까?

해결책

사용 RealPath ().

그만큼 realpath() 기능은 file_name, 동일한 파일의 이름을 지정하는 절대 경로 이름은 해상도가 포함되지 않습니다. '.', '..'또는 상징적 링크. 생성 된 PathName은 최대 최대 널리 터진 문자열로 저장되어야합니다. {PATH_MAX}바이트, 버퍼에서 resolved_name.

만약에 resolved_name 널 포인터, 동작입니다 realpath() 구현 정의입니다.


다음 예제는 SymlinkPath 인수로 식별 된 파일에 대한 절대 경로 이름을 생성합니다. 생성 된 PathName은 실제 경로 배열에 저장됩니다.

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


ptr = realpath(symlinkpath, actualpath);

다른 팁

노력하다 realpath() 안에 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);
}

또한 "getcwd"를 시도하십시오.

#include <unistd.h>

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

결과:

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

테스트 환경 :

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.

작은 경로 라이브러리도 있습니다 cwalk 크로스 플랫폼에서 작동합니다. 가지고 있습니다 cwk_path_get_absolute 하기 위해서:

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

출력 :

The absolute path is: /hello/there/world
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top