File associated with fstream object?

S

Sanyi Benczik

Is there a way to obtain the name of the file associated with a fstream
object?

For example if I have

using namespace std;
ofstream file("test.txt");

is there a function which evaluates to "test.txt"?

Thx,
Sanyi
 
J

Jack Klein

Is there a way to obtain the name of the file associated with a fstream
object?

For example if I have

using namespace std;
ofstream file("test.txt");

is there a function which evaluates to "test.txt"?

Thx,
Sanyi

There is no way to do this using standard C++. There might or might
not be a non-standard platform specific extension provided by your
compiler/OS combination. On some platforms, a single file may have
more than one name.

Of course you could always build an object that contained a
std::string with the name and a stream reference.
 
D

Dietmar Kuehl

Jack Klein said:
On some platforms, a single file may have
more than one name.

.... or none at all:

std::eek:fstream tmpfile("mytempfile");
std::remove("mytempfile");

This is fine eg. on POSIX platforms and, except for the use of the hardcoded
name, a pretty common technique to create temporary files which are to be
removed when the program dies for whatever reason.
Of course you could always build an object that contained a
std::string with the name and a stream reference.

.... or attach the name to your file object:

int const index = std::ios_base::xalloc();
std::string filename("file.name");
std::eek:fstream file(filename.c_str());
file.pword(index) = const_cast<char*>(filename.c_str());
// ...
char const* name = static_cast<char*>(file.pword(index));
 

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

Similar Threads

fstream tests 3
fstream File i/o 1
fstream Buffers 26
[c++] get() and read() function from fstream 3
fstream -> FILE* 1
Not able to open file in C++ 9
Use cout as ofstream object 5
fstream vs ofstream 6

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top