Retrieve filename from file descriptor in C Retrieve filename from file descriptor in C linux linux

Retrieve filename from file descriptor in C


You can use readlink on /proc/self/fd/NNN where NNN is the file descriptor. This will give you the name of the file as it was when it was opened — however, if the file was moved or deleted since then, it may no longer be accurate (although Linux can track renames in some cases). To verify, stat the filename given and fstat the fd you have, and make sure st_dev and st_ino are the same.

Of course, not all file descriptors refer to files, and for those you'll see some odd text strings, such as pipe:[1538488]. Since all of the real filenames will be absolute paths, you can determine which these are easily enough. Further, as others have noted, files can have multiple hardlinks pointing to them - this will only report the one it was opened with. If you want to find all names for a given file, you'll just have to traverse the entire filesystem.


I had this problem on Mac OS X. We don't have a /proc virtual file system, so the accepted solution cannot work.

We do, instead, have a F_GETPATH command for fcntl:

 F_GETPATH          Get the path of the file descriptor Fildes.  The argu-                    ment must be a buffer of size MAXPATHLEN or greater.

So to get the file associated to a file descriptor, you can use this snippet:

#include <sys/syslimits.h>#include <fcntl.h>char filePath[PATH_MAX];if (fcntl(fd, F_GETPATH, filePath) != -1){    // do something with the file path}

Since I never remember where MAXPATHLEN is defined, I thought PATH_MAX from syslimits would be fine.


In Windows, with GetFileInformationByHandleEx, passing FileNameInfo, you can retrieve the file name.