0

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! =)

2
Contributors
1
Reply
2
Views
9 Years
Discussion Span
Last Post by Ancient Dragon
0

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

}
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.