views:

25

answers:

2

Hello all,

I want to perform I/O operation in c++. I want to store a pointer to fstream object and using that same fstream I want to read and write to that file. Is it possible without using two different objects i.e ifstream for reading and ofstream for writing.

+3  A: 

Yes, an fstream is specifically intended to support both reading and writing (it derives from both ifstream and ofstream).

Jerry Coffin
Almost. It derives from `istream` and `ostream` (via `iostream`).
Mike Seymour
A: 

Yes, fstream can be used for reading and writing. Is this what you want to accomplish?

// Your fstream object
 std::fstream a("coco.txt");
 // Buffer
 char foo[100];

 // Write
 a<<"Hello"<<endl;
 // Rewind
 a.seekg(0,ios::beg);
 // Read
 a>>foo;

 // Display
 std::cout<<foo;
 // Clean up
 a.close();
Jacob
This is what I was doing expecting to write and read but one stipulation to this is file must exist. Like object instantiation of fstream does not creates a file. And that was the reason I was not able to achieve what I asked in my question.
rkb