once I have assigned a file name to a stream object, and no longer have direct access to that file name but I do have access to the stream object is there a way to extract the file name from it?

It has to know it because subsequent operations read/write and even close it. it is probably a handle ?


9 Years
Discussion Span
Last Post by dekaya

I did some googling and from this same question on several other forums it seems like there is no way to retrieve this information. The reason seems to be that the stream may not even be a file, hence the file name would be ill-defined. The recommendations were to create a class that created and returned the stream, but saved the filename which could be accessed with a getFilename() function, but it sounds like you never saw the construction of the stream, but you know it is writing to a file and want the name. I can't say personally, but it sounded, from other responses, like it is impossible.



In short: no, it's impossible to extract filename used in open file stream call from a stream object. It's a long story why...

In actual fact fstream object passed this name to filebuf object and works with this internal object which provides/consumes data. Moreover, it's possible to associate a stream with opened elsewhere streambuf. Naturally, a stream does not know external file name in this case. It's possible that associated external data source/sink is anonymous or virtual...


Is it possible to extract the filename from fstream?
> As far as I know NOT ...

> You could simply store the filename in a string-variable (for later use) ...
> Or ... you could also derive a class from fstream and store the filename in the derived class ...


There's no way to ask the stream for the filename. I know that the stat or stat64 function on Unix (it's _stat or _stat64 on Windows) returns a struct that name the filename inside. The problem is that you must provide a file descriptor or a path: that implies that you know the name of the file...


Thanks to all.
I did end up passing a pointer to my character array.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.