tags:

views:

232

answers:

3

Is there a way to retrieve path information from a file descriptor or FILE pointer?

I'm aware that this data may not always be relevant/useful for case where the file descriptor is a socket, pipe, etc.

+2  A: 

I don't believe there's any portable way, but e.g. on Linux you can call readlink on "/proc/self/fd/fileno" and the kernel will give you a path if it can, or one of various kinds of funny-looking strings if not.

hobbs
Cool, but don't confuse this with the readlink() C function, which reads the contents of the file at the end of a symbolic link.
Don Wakefield
It looks like I can scan the filesystem opening files as I go and comparing the inodes.Doing this of course is absolute rubish, and as learner mentioned there is no way to know that the first file encountered might be one of many hardlinks.I suspect the simpler, more efficient, approach would be to just extern the initial path var.
tapi
@Don: this *is* the readlink() C function, which reads the *name* of the target of a symbolic link, not the contents.
hobbs
`readlink()` works on symbolic links: it gives you the target of the link in the form of a pathname.
dmckee
@hobbs:My mistake. I don't know what API I was thinking of.
Don Wakefield
A: 

There can be one or many names for a file, so no std way. I am not sure if there can be something OS specific.

Learner
A: 

If you're lucky enough to be using Mac OS X you can use the following code:

#define _DARWIN_C_SOURCE
#include <sys/fcntl.h>
.
.
.
char pathbuf[PATH_MAX];
if (fcntl(fd, F_GETPATH, pathbuf) >= 0) {
    // pathbuf now contains *a* path to the open file descriptor
}

Note that the path you get back is not necessarily the one used to open the file... If there are hard links, especially, the path you get back will be a valid path to the file.

Kaelin Colclasure