2008-10-23 235 views
29

如何在Unix上將相對路徑轉換爲C語言中的絕對路徑? 這是否有一個方便的系統功能?獲取文件的絕對路徑

在Windows中有一個GetFullPathName功能,沒有工作,但我沒有找到在Unix類似的東西...

回答

42

使用realpath()

realpath()功能應派生, 從路徑指向 file_name,絕對路徑是 名相同的文件,其分辨率 不涉及「.」,「..」,或 符號鏈接。生成的路徑名 應存儲爲由 resolved_name指向的緩衝區中以空字符結尾的 字符串,最大爲{PATH_MAX} 字節。

如果resolved_name是空指針, realpath()的行爲是 是實現定義的。


下面的示例生成由symlinkpath 參數標識的文件 一個 絕對路徑名。生成的路徑名爲 ,存儲在actualpath數組中。

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


ptr = realpath(symlinkpath, actualpath); 
+7

的 '加一' 是沒有必要的,thuogh它不會有任何傷害。 – 2008-11-01 00:59:08

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.