FILE *foo to filename?

Richard A. O'Keefe ok at goanna.cs.rmit.oz.au
Thu Nov 1 18:53:44 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;
> what's a clean way of obtaining the filename assoctiated with foo?

There isn't any portable way, and even on a particular system

> An initial thought is stat(fileno(foo)..) to get inode number but then what?

there may not *BE* any filename associated with foo.  Consider

	foo = popen("cat >/dev/null");

fileno() isn't going to do you much good there and no more will stat().

Your best bet is to provide and use your own interface:

	FILE *mnem_fopen(...);
	void mnem_fclose(...);
	char *mnem_fname(FILE *);

where mnem_fopen() would stash the stream pointer and a copy of the
name away in a table or list or something, mnem_fclose() would clear
the entry out of the table, and mnem_fname() would return a pointer
to (the copy of) the name or NULL as appropriate.

Then on UNIX and PCs at least, there's all kinds of fun possible where
you open a file with a relative name like "foo.bar" and then change
directory; a copy of the original string won't do any more because it'll
be misinterpreted.

Then there are changes to the file system:  on UNIX and VMS at least,
a file *name* can be deleted from its directory while the *file* is
still in use.  In UNIX this is quite a useful idiom:  open a scratch
file and unlink it straight away; now you have a file which will automatically
disappear when the program terminates, but can be safely used while it's
running.  Or a file may be renamed, and a new file created with the old
name...

-- 
The problem about real life is that moving one's knight to QB3
may always be replied to with a lob across the net.  --Alasdair Macintyre.



More information about the Comp.lang.c mailing list