Getting the File Name from a File Descriptor (fd) or a File Pointer (FILE *)

Submitted by Eus
on September 3, 2009 - 12:51am

While developing the logger for GNU/Linux Anywhere USB Controller (https://savannah.nongnu.org/projects/awusb/), I created the following function that will store a `FILE *' into a global table for a later retrieval:

static int
save_open_file (FILE *log_file);

I thought I could take the name of the file through `FILE *' or its fd (file descriptor) using a libc (C library) function like `fstat'. But, I was badly mistaken.

Trying to find the function using `apropos' in vain, I googled for it. Forming the keywords was a bit hard. But, at the end I landed on http://www.unix.com/unix-dummies-questions-answers/23852-file-descriptor... in which Jim McNamara says that it is not possible to retrieve the filename since an fd, and indirectly, `FILE *' refers to an inode number instead of a filename. Filename, on the other hand, is translated by the filesystem into an inode number, after which all file I/O operations operate on the inode number.

With another keywords, I found this post http://www.codeguru.com/forum/archive/index.php/t-179423.html in which AlanGRutter says that it is possible to do so by accessing field `_tmpfname' (temporary file name) of `FILE'. However, it turned out that such a field is only defined for a particular C library, and therefore, it is not portable.

At the end, both posts suggest the use of a self-defined structure to store the filename. So, I modified my function as follows:

static int
save_open_file (const char *filename, FILE *log_file);

To conclude, getting the filename from a file descriptor (fd) or a file pointer (FILE *) is generally not possible. As a C programmer, one must be aware that if a filename is needed after opening the file, the filename must be propagated along with the corresponding `fd' or `FILE *'.