Given a stdio FILE *
pointer, is there a method by which I can discover the name of the (opened) file?
views:
134answers:
3No, there isn't. Apart from anything else, the FILE * may not refer to a named file. If your application needs this facility, you wil need to maintain some kind of map from open FILE *s to the file name you used to open them.
There is no standard defined portable solution. However, you can take a look at your OS provided API set. POSIX systems have a fstat
function that takes a descriptor (not a FILE *
) and returns some information.
It looks (from here) that on POSIX systems you can use fileno() to get the file descriptor from a FILE*, then use fstat to get the stat info from the file descriptor. The stat structure contains the device number and inode number. You can check the filesystem for files which match the inode. This will obviously take some time for a filesystem full of stuff.
The reason that this isn't really possible (as explained in the linked article) is that a stream can have no filename if it's something like stdin or stdout, or if it's an open file that has been deleted. It can have multiple names because of hardlinks as well.
The linked article mentions this comp.lang.c FAQ which outlines the insolubility of this problem in brief.
EDIT: Thanks for the correction.