Getting a File Name from a FILE *

A

Ancient_Hacker

Dale Pennington wrote:

Not easily or portably, but here's a few hints:

(0) See if your debugger is smart enough to do this.

(1) First get the source to your C runtime library. Look at the code
for fopen() and particularly the declaration of a FILE structure. If
you don't have the code, step thru it with *horrors* a debugger.
Somewhere pretty early it will call the system API or the C open() to
open a file. Which in almost every OS, returns a small integer. Most
if not all fopens() nowadays put that thing, often called a "file
handle", into fopen's open file table, then fopen returns the address
into that table. Often if you look *horrors* at your link map,
you'll see fopen() exports that table. With a little peeking into the
FILE * structure you should be able to get a hold of the handle for the
file. Then many if not most systems have a "GetFileInfoFromHandle()"
API. Whew.

*Not* widely portable, but has been known to be doable and has saved
many a butt when the going got tough.
 
R

Richard Bos

CBFalconer said:
Why? It is still the name under which it was opened.

Yes, but it's not any more. This can be misleading.
Trying to reopen it will probably fail.

Probably being the operative word here.
The things that get fouled include
anonymous temporary files, and i/o streams.

Yes, but in those cases there simply is no file name, so you can return
a null pointer instead. That, at least, is clear and correct.

Richard
 
S

SM Ryan

C's early days were on the machines where 65536 bytes total
code and data was a lot of room. Few c library routines
allocate memory and that would be necessary to save the
file name.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top