2014-12-02 132 views
6

請幫助我沒有得到如何實現一個函數,該函數使用C/C++返回該文件的完整路徑?如何通過提供文件名來獲取完整路徑?

+3

如果有什麼不同的位置兩個同名文件? – Himanshu 2014-12-02 11:14:10

+0

你有文件名或文件指針嗎? – nikhilr57 2014-12-02 11:15:33

+2

相同:http://stackoverflow.com/questions/1661982/how-do-i-get-the-full-path-for-a-filename-command-line-argument – Neska 2014-12-02 11:17:25

回答

11

UNIX/Linux的:

#include <limits.h> 
#include <stdlib.h> 

char *full_path = realpath("foo.dat", NULL); 

... 

free(full_path); 

或:

char full_path[PATH_MAX]; 
realpath("foo.dat", full_path); 

的Windows:

#include <windows.h> 

TCHAR full_path[MAX_PATH]; 

GetFullPathName(_T("foo.dat"), MAX_PATH, full_path, NULL); 
+0

有沒有通用的解決方案? – Pedro77 2017-04-24 13:20:49

+1

在C++ 17中,有['std :: filesystem :: canonical'](http://en.cppreference.com/w/cpp/filesystem/canonical)。對於較老的標準,它可作爲['boost :: filesystem'](http://www.boost.org/doc/libs/1_64_0/libs/filesystem/doc/index.htm)庫的一部分。不過,我不認爲C標準庫中有類似的功能。 – Wintermute 2017-06-05 12:44:15

相關問題