tags:

views:

333

answers:

3

I know it is possible to get an absolute path of a file with realpath() function. However, according to BUGS section the manpage, there are some problem in its implementation. The details are following:


BUGS

Avoid using this function. It is broken by design since (unless using the non-standard resolved_path == NULL feature) it is impossible to determine a suitable size for the output buffer, resolved_path. According to POSIX a buffer of size PATH_MAX suffices, but PATH_MAX need not be a defined constant, and may have to be obtained using pathconf(3). And asking pathconf(3) does not really help, since on the one hand POSIX warns that the result of pathconf(3) may be huge and unsuitable for mallocing memory. And on the other hand pathconf(3) may return -1 to signify that PATH_MAX is not bounded.

The libc4 and libc5 implementation contains a buffer overflow (fixed in libc-5.4.13). Thus, set-user-ID programs like mount(8) need a private version.


So, the question is what is the best practice to get the absolute path of a file?

+2  A: 

From the shell, I can get a full path using readlink -f $FILE. There's a readlink() function in glibc, maybe that'll help you.

# man 2 readlink
eduffy
I have read the source code of readlink command in coreutils package. There is a simple solution-just define the PATH_MAX to 1024!!!! -__-!!!
jcadam
+2  A: 

Use getcwd() and readlink() which allows to give a buffer size to reimplement realpath(). Note that you have to resolve symbolic links, "." and ".." from left to right to do it correctly.

AProgrammer
A: 

Duplicate of "Programatically retrieving the absolute path of an OS X command-line app"?

bortzmeyer
No. They are not the same thing. I want to know how to get absolute path of an ordinary file rather than the path of executable.
jcadam