tags:

views:

134

answers:

3

Given a stdio FILE * pointer, is there a method by which I can discover the name of the (opened) file?

+2  A: 

No, 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.

anon
+1  A: 

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.

dirkgently
+8  A: 

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.

Matt Kane
Thanks for more than just the "no you can't" answer.
Jamie
fstat() is used to describe the file that the file descriptor has open. You use fileno() to get the file descriptor from the file pointer. Note that the inode might not be found, or there might be multiple possible names for the file (depending on the number of hard links).
Jonathan Leffler