views:

374

answers:

5

How to get the absolute path for a given relative path programmatically in Linux?

Incase of Windows we have the _fullpath() API. In other words, I mean what is analogous API to _fullpath of Windows in Linux?

+3  A: 

Try realpath:

$ man realpath

This is also available in BSD, OS X, et al.

Paul R
+1 Didn't know this and had to implemented similar function myself recently :(
qrdl
+2  A: 

There is the realpath from stdlib.h

Otto Allmendinger
I immediately thought of realpath, too, but I was *stunned* -- *stunned* I say -- when I saw your answer showing that `realpath` is in `stdlib.h`. Surely that *can't* be true, considering that `realpath` is not part of the C library. Lo and behold, it's true. I'm dumbfounded. What's a well-formed program that defines its own function named `realpath` to do? Those POSIX guys have run amok! *Amok* I say!
Dan Moulding
Dan: So long as they invoke their compiler in "strictly conforming" mode and don't define any macros that invoke undefined behaviour (like `_XOPEN_SOURCE`), they should be OK.
caf
+3  A: 

As Paul mentioned, use realpath(). Please note though, that since many file systems in Linux support hard links, any given directory can have a number of different absolute paths.

unwind
Any given file can, for sure. Hard-links to directories isn't necessarily supported. Symlinks also cause some confusion when it come sto determining the "real" path.
Vatine
@unwind, Thanks for the Info. If due to hard links, if a given directory resolves to multiple different absolute paths, what will be the behaviour of realpath API?
Jay
Hardlinks to directories are considered evil and forbidden by most filesystems.
edgar.holleis
@Vatine: realpath resolves symbolic links
Otto Allmendinger
I am a little confused. Is it possible that a given directory resolves to many different absolute paths? If yes, then what will be the behaviour realpath?
Jay
@Jay it doesn't affect resolving a relative path to an absolute path.
Otto Allmendinger
`realpath` resolves the name in the way you would expect - by (recursively) flattening out `/../` and `/./` components and resolving symlinks. The "multiple paths" issue just means that the name you get out at the end isn't necessarily unique for a given file (since a file does not necessarily have a single "true name").
caf
+2  A: 

Check out the realpath function.

#include <stdlib.h> 
#include <stdio.h> 
int main() 
{ 
        char resolved_path[100]; 
        realpath("../../", resolved_path); 
        printf("\n%s\n",resolved_path); 
        return 0; 
} 
Martin Wickman
A: 

The is also another useful way, like "readlink -m $filename"

First of all, it works without requirement for target file to exist. Secondly, it will handle symlinks and get really real path.

Zebooka