Is it possible to get the filename of a file descriptor (Linux) in C?
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.