FILE *foo to filename?

Bill Poser poser at csli.Stanford.EDU
Wed Oct 31 16:32:40 AEST 1990


In article <272cd831-5edcomp.lang.c at vpnet.chi.il.us> akcs.dgy at vpnet.chi.il.us (Donald Yuniskis) writes:
>Given:
>  FILE *foo;
>whats a clean way of obtaining the filename assoctiated with foo?
>An initial thought is stat(fileno(foo)..) to get inode number but then what?
>Any help is appreciated... thx, dgy

If you are opening the file to begin with, just keep the name around.
I sometimes keep a table of file information, say an array or linked list
of structs something like:

	struct FileInfo{
		char *name;
		FILE *fp;
		short mode;
	};

If you're not opening the files yourself of course you can't do this.
What you do becomes operating system dependant - the file system is
not part of C. On a UNIX system, as suggested, you have to try to
match the inode number obtained from stat with a pathname. This is
not easy since the system does not maintain pointers from inodes
to paths, only from paths to inodes (that is, directories). You can
traverse the directory tree looking for matches to the inode number,
but this can be quite time-consuming. Note also that the path corresponding
to an inode number is not unique - there can be many links to a single
inode.

I'm curious, though, why anyone would want to do this.
It isn't terribly common to pass file pointers around in contexts
where one cannot also pass the name if desired.  Does the
application involve a child that inherits the parent's file descriptors
but not its data?



More information about the Comp.lang.c mailing list