473,386 Members | 1,652 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Getting a File Name from a FILE *

I find myself in the odd situation of trying to determine the name of a file
that has been opened somewhere else with an fopen call, so all I have is the
FILE * from that fopen call. I perused my favorite online C API reference
and did not find a method, but hopefully that means I did not look in the
right places (we all know how easy it is to find stuff once you know where
to acutally look).

So, the question, given a FILE *, can one get back to the name/path of the
file that was opened, and if so, how ?

Thanks for the assist,
Dale Pennington
Aug 22 '06 #1
22 1621
Dale Pennington wrote:
So, the question, given a FILE *, can one get back to the name/path of the
file that was opened, and if so, how ?
No.

A FILE * may have many names/paths in the filesystem that refer to the
underlying file, or none at all, and there's no way in standard C to go
from a FILE * to a list of zero or more filenames that correspond to
it.

offtopic: Depending on your platform and needs, you might look at
something like lsof if you really need to do this. You're really best
off eliminating the need, though.

Aug 22 '06 #2


Dale Pennington wrote On 08/22/06 17:14,:
I find myself in the odd situation of trying to determine the name of a file
that has been opened somewhere else with an fopen call, so all I have is the
FILE * from that fopen call. I perused my favorite online C API reference
and did not find a method, but hopefully that means I did not look in the
right places (we all know how easy it is to find stuff once you know where
to acutally look).

So, the question, given a FILE *, can one get back to the name/path of the
file that was opened, and if so, how ?
This is Question 19.15 in the comp.lang.c Frequently
Asked Questions (FAQ) list

http://www.c-faq.com/

.... and you're not going to like the answer. :-(

--
Er*********@sun.com

Aug 22 '06 #3
"Dale Pennington" <da***************@boeing.comwrites:
So, the question, given a FILE *, can one get back to the name/path of the
file that was opened, and if so, how ?
This is a FAQ.

19.15: How can I recover the file name given an open stream or file
descriptor?

A: This problem is, in general, insoluble. Under Unix, for
instance, a scan of the entire disk (perhaps involving special
permissions) would theoretically be required, and would fail if
the descriptor were connected to a pipe or referred to a deleted
file (and could give a misleading answer for a file with
multiple links). It is best to remember the names of files
yourself as you open them (perhaps with a wrapper function
around fopen()).

--
Just another C hacker.
Aug 22 '06 #4
Dale Pennington wrote:
I find myself in the odd situation of trying to determine the name of a file
that has been opened somewhere else with an fopen call, so all I have is the
FILE * from that fopen call. I perused my favorite online C API reference
and did not find a method, but hopefully that means I did not look in the
right places (we all know how easy it is to find stuff once you know where
to acutally look).

So, the question, given a FILE *, can one get back to the name/path of the
file that was opened, and if so, how ?
Save it yourself when it is opened. There is no standard way to recover
such information. If your program managed to fopen() the file, then you
already have the information.
Aug 22 '06 #5
Martin Ambuhl <ma*****@earthlink.netwrites:
Dale Pennington wrote:
>I find myself in the odd situation of trying to determine the name
of a file that has been opened somewhere else with an fopen call, so
all I have is the FILE * from that fopen call. I perused my favorite
online C API reference and did not find a method, but hopefully that
means I did not look in the right places (we all know how easy it is
to find stuff once you know where to acutally look).
So, the question, given a FILE *, can one get back to the name/path
of the file that was opened, and if so, how ?

Save it yourself when it is opened. There is no standard way to
recover such information. If your program managed to fopen() the
file, then you already have the information.
That's correct (some systems *might* provide some non-portable way to
get this information, but as far as I know many systems don't.)

But the obvious solution, remembering the name when you call fopen(),
isn't always a possibility. Programs are not always monolithic; the
code that calls fopen() might have been written by someone else, and
you might not be able to modify it.

It wouldn't have been entirely nonsensical for the C standard to have
specified, say, an fname() function that returns a pointer to a copy
of the string that was passed to fopen(), or perhaps to some canonical
representation. The behavior for stdin, stdout, and stderr, and for
streams not opened with fopen(), would have to be defined, but that
wouldn't be an insurmountable problem. Such a thing might have been
useful, and it exists in at least one non-C language that I know of.

In C, it doesn't exist because it doesn't exist. If you can, remember
the name when you open the file. If you can't do that, try to figure
out a way to avoid the requirement in the first place.

--
Keith Thompson (The_Other_Keith) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Aug 22 '06 #6
Keith Thompson wrote:
[...]
It wouldn't have been entirely nonsensical for the C standard to have
specified, say, an fname() function that returns a pointer to a copy
of the string that was passed to fopen(), or perhaps to some canonical
representation. [...]
Clearly, fname() would have to be allowed to fail, possibly
by returning NULL. This would leave the O.P. in the uncomfortable
situation of having a function that might solve his problem, but
might also just throw up its hands and leave his situation unimproved.

But let's suppose an fopen() that squirrels away a copy of its
first argument for later use by fname(). Such an fopen() would need
to be able to fail for lack of enough memory to stash the filename
string, even if the program never intended to call fname() and the
string would never be used. ("ECATCH22: insufficient unnecessary
memory.") Bummer!

Finally, systems capable of running multiple programs at the same
time exist, and though simultaneity is not "officially recognized" by
the C Standard, it must nonetheless be acknowledged. The file name
with which fopen() successfully opened a file, even if saved verbatim,
might no longer be valid when fname() is called, or might even lead
to a completely different file. (Some security exploits have relied
on exactly this situation.)

Putting all this together, I'd still agree that "it wouldn't have
been entirely nonsensical" to specify fname(). I cannot believe,
though, that it would have been entirely sensical.

--
Eric Sosman
es*****@acm-dot-org.invalid
Aug 23 '06 #7
Eric Sosman wrote:
>
.... snip ...
>
But let's suppose an fopen() that squirrels away a copy of its
first argument for later use by fname(). Such an fopen() would need
to be able to fail for lack of enough memory to stash the filename
string, even if the program never intended to call fname() and the
string would never be used. ("ECATCH22: insufficient unnecessary
memory.") Bummer!
No, all it has to do is squirrel away a NULL with which to answer
any future fname call. Then only the fname fails.

--
Chuck F (cb********@yahoo.com) (cb********@maineline.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.netUSE maineline address!
Aug 23 '06 #8

Eric Sosman wrote:
Keith Thompson wrote:
[...]
It wouldn't have been entirely nonsensical for the C standard to have
specified, say, an fname() function that returns a pointer to a copy
of the string that was passed to fopen(), or perhaps to some canonical
representation. [...]

Clearly, fname() would have to be allowed to fail, possibly
by returning NULL. This would leave the O.P. in the uncomfortable
situation of having a function that might solve his problem, but
might also just throw up its hands and leave his situation unimproved.
But this is frequently the case with C functions. This is QOI.
But let's suppose an fopen() that squirrels away a copy of its
first argument for later use by fname(). Such an fopen() would need
to be able to fail for lack of enough memory to stash the filename
string, even if the program never intended to call fname() and the
string would never be used. ("ECATCH22: insufficient unnecessary
memory.") Bummer!
Doesn't seem to be a major problem. Add one byte to the minimum
requirement, and use this to signal the memory problem to fname.
fopen() would not fail, fname() would.
>
Finally, systems capable of running multiple programs at the same
time exist, and though simultaneity is not "officially recognized" by
the C Standard, it must nonetheless be acknowledged. The file name
with which fopen() successfully opened a file, even if saved verbatim,
might no longer be valid when fname() is called, or might even lead
to a completely different file. (Some security exploits have relied
on exactly this situation.)
This can happen without needing multiple programs.
We have that fopen(fname(fp)) might not succeed, or might not point
to the same file as fp. I don't however see a security hole. fname()
should return only a string, so if this string refers to a file that
the
program does not have permission to open the fopen(fname(fp)) should
fail.
The fact that a previous fopen() to the same string succeeded
should not influence things.
>
Putting all this together, I'd still agree that "it wouldn't have
been entirely nonsensical" to specify fname(). I cannot believe,
though, that it would have been entirely sensical.
I disagree.

-William Hughes

Aug 23 '06 #9
Dale Pennington wrote:
I find myself in the odd situation of trying to determine the name of a file
that has been opened somewhere else with an fopen call, so all I have is the
FILE * from that fopen call. I perused my favorite online C API reference
and did not find a method, but hopefully that means I did not look in the
right places (we all know how easy it is to find stuff once you know where
to acutally look).

So, the question, given a FILE *, can one get back to the name/path of the
file that was opened, and if so, how ?
Out of curiousity, why the need? As others have pointed out, it's
not going to be easy, and removing the need is probably your
best solution. I ask because I can remember long ago thinking
that I had that exact same need, and found that it wasn't really
the name I needed but some other piece of information which
I thought was only attainable from the name (eg a mount point,
or a new FILE *). Presently, the only time I ever need the name
is immediately after fopen, and I only use it for use in printing
the log message that fopen() failed. Occasionally I'll hold onto
the name to log an ferror(), but I'm happy logging a nameless
message as well, since it's usually pretty easy for the reader
of the message to deduce the problem without the filename.
(eg, if the read() caused an error, it's because the
mount failed, and has nothing to do with a particular file.
Having the pathname in the log message might help discover
the failing disk, but that's usually obvious from other sources.)

Aug 23 '06 #10
Bill Pursell wrote:
>
Dale Pennington wrote:
I find myself in the odd situation of trying to determine the name of a file
that has been opened somewhere else with an fopen call, so all I have is the
[...]
So, the question, given a FILE *, can one get back to the name/path of the
file that was opened, and if so, how ?

Out of curiousity, why the need?
[...]

I wrote a wrapper around fopen/fclose (as well as the POSIX open and
close functions) to store the filename. Should some error occur later
on while accessing the file, the filename can be included in the error
message. (The filename is used internally for some other things as
well, but error messages are the main reason.)

Yes, this is an admittedly limited case, but I think it's a perfectly
valid example of "why the need?" And, should an error occur on
something other than one of the files opened by the wrappers, then the
error simply doesn't display the filename.

--
+-------------------------+--------------------+-----------------------+
| Kenneth J. Brody | www.hvcomputer.com | #include |
| kenbrody/at\spamcop.net | www.fptech.com | <std_disclaimer.h|
+-------------------------+--------------------+-----------------------+
Don't e-mail me at: <mailto:Th*************@gmail.com>

Aug 23 '06 #11
William Hughes wrote:
But this is frequently the case with C functions. This is QOI.
Not even dictionary.com knows what QOI means :-(

Aug 23 '06 #12
Keith Thompson <ks***@mib.orgwrote:
It wouldn't have been entirely nonsensical for the C standard to have
specified, say, an fname() function that returns a pointer to a copy
of the string that was passed to fopen(), or perhaps to some canonical
representation. The behavior for stdin, stdout, and stderr, and for
streams not opened with fopen(), would have to be defined, but that
wouldn't be an insurmountable problem. Such a thing might have been
useful, and it exists in at least one non-C language that I know of.
Then that non-C language is misleading in some cases. It is possible
under some OSes to delete a file from a directory while a program has it
opened. If the FILE were to remember the original name, that name would
then be wrong.

Richard
Aug 23 '06 #13
sp****@gmail.com wrote:
William Hughes wrote:
But this is frequently the case with C functions. This is QOI.

Not even dictionary.com knows what QOI means :-(
Naturally, since it's not a word. Try <http://www.acronymfinder.com/>
instead.

Richard
Aug 23 '06 #14
Richard Bos wrote:
sp****@gmail.com wrote:
William Hughes wrote:
But this is frequently the case with C functions. This is QOI.
Not even dictionary.com knows what QOI means :-(

Naturally, since it's not a word. Try <http://www.acronymfinder.com/>
instead.
But dictionary.com knows the meaning of many acronyms
and if it doesn't it automatically forwards you to the page
of www.acronymfinder.com which does have the meaning.
Since in this case dictionary.com didn't do that I assumed
that acronymfinder.com didn't have the meaning either but
it actually does. So perhaps it's a bug with dictionary.com

Aug 23 '06 #15
sp****@gmail.com wrote:
William Hughes wrote:
>But this is frequently the case with C functions. This is QOI.

Not even dictionary.com knows what QOI means :-(
But we do :-) Quality of Implementation.

--
Chuck F (cb********@yahoo.com) (cb********@maineline.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.netUSE maineline address!
Aug 23 '06 #16
Richard Bos wrote:
Keith Thompson <ks***@mib.orgwrote:
>It wouldn't have been entirely nonsensical for the C standard to have
specified, say, an fname() function that returns a pointer to a copy
of the string that was passed to fopen(), or perhaps to some canonical
representation. The behavior for stdin, stdout, and stderr, and for
streams not opened with fopen(), would have to be defined, but that
wouldn't be an insurmountable problem. Such a thing might have been
useful, and it exists in at least one non-C language that I know of.

Then that non-C language is misleading in some cases. It is possible
under some OSes to delete a file from a directory while a program has it
opened. If the FILE were to remember the original name, that name would
then be wrong.
Why? It is still the name under which it was opened. Trying to
reopen it will probably fail. The things that get fouled include
anonymous temporary files, and i/o streams.

--
Chuck F (cb********@yahoo.com) (cb********@maineline.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.netUSE maineline address!
Aug 23 '06 #17
sp****@gmail.com wrote:
>
Richard Bos wrote:
>sp****@gmail.com wrote:
>>William Hughes wrote:

But this is frequently the case with C functions. This is QOI.

Not even dictionary.com knows what QOI means :-(

Naturally, since it's not a word. Try <http://www.acronymfinder.com/>
instead.

But dictionary.com knows the meaning of many acronyms
and if it doesn't it automatically forwards you to the page
of www.acronymfinder.com which does have the meaning.
Since in this case dictionary.com didn't do that I assumed
that acronymfinder.com didn't have the meaning either but
it actually does. So perhaps it's a bug with dictionary.com
It has to do withthe QOI of dictionary.com :-)

--
Chuck F (cb********@yahoo.com) (cb********@maineline.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home.att.netUSE maineline address!

Aug 23 '06 #18
CBFalconer wrote:
Richard Bos wrote:
>>Keith Thompson <ks***@mib.orgwrote:

>>>It wouldn't have been entirely nonsensical for the C standard to have
specified, say, an fname() function that returns a pointer to a copy
of the string that was passed to fopen(), or perhaps to some canonical
representation. The behavior for stdin, stdout, and stderr, and for
streams not opened with fopen(), would have to be defined, but that
wouldn't be an insurmountable problem. Such a thing might have been
useful, and it exists in at least one non-C language that I know of.

Then that non-C language is misleading in some cases. It is possible
under some OSes to delete a file from a directory while a program has it
opened. If the FILE were to remember the original name, that name would
then be wrong.


Why? It is still the name under which it was opened. Trying to
reopen it will probably fail. The things that get fouled include
anonymous temporary files, and i/o streams.
I guess it all gets back to what use the program plans
to make of the fname() string. If it's just for "decorative"
purposes (c.f. __FILE__ or argv[0]), it probably doesn't matter
much that the string might no longer be an accurate name for
the stream's file. But if the program makes "substantive" use
of the string -- passing it to rename(), say -- then accuracy
becomes an issue.

How much of an issue? "Bless you, it all depends!"

--
Eric Sosman
es*****@acm-dot-org.invalid
Aug 23 '06 #19

"Bill Pursell" <bi**********@gmail.comwrote in message
news:11**********************@i42g2000cwa.googlegr oups.com...
Dale Pennington wrote:

Out of curiousity, why the need? As others have pointed out, it's
<snipped>
>
I am responsible for a support library that other application writers in my
group use. The library provides a some file logging support. We recently
added a feature to support logs larger than the max filesize (by splitting
into multiple files with a specified naming convention). For the new
implementaion we changed to API from passing a FILE * to passing a custom
structure that contains the FILE * as well other information to support the
splitting operation
(including the file name).

Now for a specific test at a remote site with an older version of the code,
they want to retrofit the large files in without having to touch all the
application code. And while the original API provided an open function folks
were supposed to use, some did not (bad application programmers!). I was
hoping the get the file name on files opened with fopen vice my log API to
make the temporary implemention easier.

Thanks
Dale Pennington
Aug 23 '06 #20

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.

So, the question, given a FILE *, can one get back to the name/path of the
file that was opened, and if so, how ?

Thanks for the assist,
Dale Pennington
Aug 23 '06 #21
CBFalconer <cb********@yahoo.comwrote:
Richard Bos wrote:
Keith Thompson <ks***@mib.orgwrote:
It wouldn't have been entirely nonsensical for the C standard to have
specified, say, an fname() function that returns a pointer to a copy
of the string that was passed to fopen(), or perhaps to some canonical
representation. The behavior for stdin, stdout, and stderr, and for
streams not opened with fopen(), would have to be defined, but that
wouldn't be an insurmountable problem. Such a thing might have been
useful, and it exists in at least one non-C language that I know of.
Then that non-C language is misleading in some cases. It is possible
under some OSes to delete a file from a directory while a program has it
opened. If the FILE were to remember the original name, that name would
then be wrong.

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
Aug 24 '06 #22
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.

--
SM Ryan http://www.rawbw.com/~wyrmwif/
Mention something out of a Charleton Heston movie, and suddenly
everybody's a theology scholar.
Aug 24 '06 #23

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Richard | last post by:
Hi All, I am using Visual C++ .Net to create a windows forms application and I am getting the following errors when I do a MessageBox::Show in my Form1.cpp file: Form1.cpp(19): error C2653:...
2
by: asad | last post by:
Hello friends, i need some help in getting uploaded file name, i am uploading 2 files and i want to get only the filename of these 2 file not a full path so pls tell me which function or technique...
0
by: ruju00 | last post by:
I am getting an error in Login() method of the following class FtpConnection public class FtpConnection { public class FtpException : Exception { public FtpException(string message) :...
1
by: pukya78 | last post by:
Hi, I am trying to get the current file and the line number which is getting executed. I used: MessageBox.Show(New StackTrace(New StackFrame(True)).GetFrame(0).GetFileLineNumber) which gives me...
1
by: iwdu15 | last post by:
hi, how can i get the icon associated with a certain file type? thanks -- -iwdu15
4
by: AshishMishra16 | last post by:
HI friends, I am using the Flex to upload files to server. I m getting all the details about the file, but I m not able to upload it to Server. Here is the code i m using for both flex & for...
1
by: sbettadpur | last post by:
hello i am calling .exe file through my php script. i.e. using exec or system command, i am running exe file that exe file will create on txt file which contains who has logged into domain(i.e....
5
by: tshad | last post by:
I have the following class in my VS 2008 project that has a namespace of MyFunctions. ********************************* Imports System Imports System.Text.RegularExpressions Namespace...
9
vikas251074
by: vikas251074 | last post by:
I am not getting date value in spite of my good effort. This code was working in my last office where I work. Now I am trying to work at my home pc. but not getting date value. Any can help me why...
7
vikas251074
by: vikas251074 | last post by:
I am getting error above in following code since few days giving tension day and night. How can I solve this? I am facing since Oct.25. in line no. 362 After doing a lot of homework, I am...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.