2008-10-23 7 views
29

유닉스에서 상대 경로를 C의 절대 경로로 변환하려면 어떻게해야합니까? 편리한 시스템 기능이 있습니까? Windows에서파일의 절대 경로 얻기

가 작업을 수행하는 GetFullPathName 기능이 있습니다,하지만 난 유닉스에 비슷한 ...

답변

42

사용 realpath()를 찾지 못했습니다. 경로명에서

realpath() 함수를 도출한다 누구 해상도 이름과 동일한 파일이, '..를'. '을 포함하거나 심볼릭 링크하지 않는 file_name 절대 경로가 가리키는 . 생성 된 경로 이름 은 문자열로 최대 {PATH_MAX} 바이트까지 저장되며 resolved_name이 가리키는 버퍼에 저장됩니다.

resolved_name가 널 포인터라면, 는 realpath()의 동작은 구현 정의이다.


다음은 symlinkpath 인수에 의해 식별 된 파일 위한 절대 경로를 생성한다. 생성 된 경로 이름은 이고 실제 경로 배열에 저장됩니다.

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


ptr = realpath(symlinkpath, actualpath); 
+7

'더하기 하나는'그 thuogh 필요하지 않습니다 어떤 해를 끼치 지 않을 것입니다. –

+2

Windows에서'GetFullPathName'은 존재하지 않는 파일에서도 작동합니다. 'realpath'는 경로가 존재해야합니다. 경로 또는 파일을 만들 때 이런 종류의 싫증이납니다. – Joakim

0

또한 "에 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 

테스트 환경 :

[email protected]$/ lsb_release -a 
No LSB modules are available. 
Distributor ID: Debian 
Description: Debian GNU/Linux 8.6 (jessie) 
Release: 8.6 
Codename: jessie 
[email protected]$/ uname -a 
Linux localhost 3.16.0-4-amd64 #1 SMP Debian 3.16.36-1+deb8u2 (2016-10-19) x86_64 GNU/Linux 
[email protected]$/ 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.