[lug] C++, fstream, finding name of open stream

Jonathan Briggs zlynx at acm.org
Fri Dec 7 11:46:23 MST 2001


D. Stimits wrote:

>Does anyone here know if there is a way to extract the file name and
>path (I need full path) from an ifstream or fstream in general under
>Linux/g++? I've been looking through the headers for fstream and related
>files, there doesn't seem to be any direct mechanism for finding the
>file name and path when given an open fstream (I'm using ifstream). I'm
>assuming that if there is a way, it is probably system-dependent.
>
>D. Stimits, stimits at idcomm.com
>_______________________________________________
>Web Page:  http://lug.boulder.co.us
>Mailing List: http://lists.lug.boulder.co.us/mailman/listinfo/lug
>
Ask yourself if you really need to do this.  If you do for some reason, 
keep in mind that there is no guarantee the file you have open still has 
the same name!  The file may have been renamed or deleted while you are 
using it.  Your file handle is still valid, but the filename may be 
different or completely gone.

Forgetting this has been a cause of several security holes in the past.

If you still need the filename, I'd recommend using a completely 
portable solution.  Derive your own class from ifstream.  Write new 
constructor and open functions that saves the filename into a member 
variable and write an access function to get the value back.

I just finished looking at the GCC 3.0 libio source.  It doesn't look 
like ifstream stores the filename anywhere.  It is only used to open the 
file.  After that, it's gone.




More information about the LUG mailing list