As far as I understand, fstream allows you to write and read the same opened file. Also it has two "file pointers", one for reading and other for writing. But if I read one line from file first, and then trying to write in it - file doesn't change, even if I use flush() after.
There is a way to fix this - use seekp() and move "file pointer" somewhere. But I don't understand why does it work that way. And there is some strange detail - if I check file pointers with tellp() before and after writing - they actually change their position! Maybe I am mistaken in something, and I will be grateful for any help
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
fstream file("Output.txt");
string line = "";
getline(file, line);
cout << "Read line: " << line << endl;
cout << "tellg: " << file.tellg() << endl;
cout << "tellp: " << file.tellp() << endl;
cout << "rdstate: " << file.rdstate() << endl;
cout << "------------------------------- " << endl;
file.write("test", 4);
file.flush();
cout << "After writing:\nrdstate: " << file.rdstate() << endl;
cout << "tellg: " << file.tellg() << endl;
cout << "tellp: " << file.tellp() << endl;
file.close();
cout << "------------------------------- " << endl;
cout << "After closing:\nrdstate: " << file.rdstate() << endl;
}
So I have a file:
a
b
c
d
It doesn't change after program worked. There are no any errors according to rdstate()
Program output:
Read line: a
tellg: 3
tellp: 3
rdstate: 0
After writing:
rdstate: 0
tellg: 9
tellp: 9
After closing:
rdstate: 0