duplicate filestream

S

ss

I need to duplicate the filestream objects. The file pointer in two objects
should always be in sync.
How can we do it?
Openeing same file in two different fstream objects is not working. The file
pointers go out of sync with each other.
 
J

John Harrison

ss said:
I need to duplicate the filestream objects. The file pointer in two objects
should always be in sync.
How can we do it?
Openeing same file in two different fstream objects is not working. The file
pointers go out of sync with each other.

That's not possible I think. Obvious answer would be to use two pointers to
the same fstream object. You could also use two smart pointers if you were
concerned about object lifetime issues.

john
 
D

Dave Moore

I guess you are talking about the case where you want objects of two
or more different classes to put their output on the same stream?
That's not possible I think.

Well .. I think you could use the low level utilities dealing with the
underlying streambuf to sync the filepointers manually:
std::eek:fstream file1("junk.tmp");
std::eek:fstream file2("junk.tmp");

file2.seekp(file1.tellp());

but you would have to do this everytime you accessed either stream.
Also, I guess you can't (or don't want to) access both ofstream
objects at the same time, because then wouldn't need two of them,
right?
Obvious answer would be to use two pointers to
the same fstream object. You could also use two smart pointers if you were
concerned about object lifetime issues.

I think this is a generally better solution, but it would IMO be even
better to do it with a reference, if that is possible:

#include <fstream>
using std::eek:fstream;

class A {
ofstream& output;
public:
A(ofstream& o) : output(o) {}
// ...
};

class B {
ofstream& output;
public:
B(ofstream& o) : output(o) {}
// ...
};

int main() {
ofstream foo("junk.tmp");
A a(foo);
B b(foo);

// code using a and b

return 0;
}

Objects a and b in the example about will both put their output in
junk.tmp. AFAICT, the only place where complications might arise is
on a multithreaded system, but I know only enough about that to say
that it *might* be a problem. Of course, woe betide you if foo is
destructed before a and b.

HTH, Dave Moore
 

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
474,167
Messages
2,570,910
Members
47,453
Latest member
MadelinePh

Latest Threads

Top