Hi,

I would like to know if it is possible to read a file and write to the same file at the same time.
For example, if I have

#include <fstream>
// and other headers

string temp_string;
char result;


fstream studfile;
studfile.open("student.dat", ios::in | ios::out); // Is this correct?

while (!studfile.eof() ) {
     getline ( studfile, temp_string);
     studfile << "Results: " << result << endl;
}

Is there any way to manipulate a .dat file while reading it?
I've checked quite a couple of sites, but there are only solutions for binary files..

Thanks! =)

This might actually result in an infinite loop because it keeps expanding the file as the loop progresses

#include <fstream>
// and other headers

string temp_string;
char result;
long pos;


fstream studfile;
studfile.open("student.dat", ios::in | ios::out); // Is this correct?

while (getline ( studfile, temp_string) ) 
{
     pos = studfile.tellg(); // get current file position     
     studfile.seekg(0, ios::end); // seek to end of file
     studfile << "Results: " << result << endl << flush();
     studfile.seekp(pos, ios::beg); // seek back to previous read position

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.