While writing some code to update a position in a binary file I noticed something strange. Consider this example code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main() {
char tmp;
string s;
fstream fs;
fs.open("test.txt", fstream::out);
fs << "blub" << endl;
fs.close();
fs.open("test.txt", fstream::in);
fs >> s;
cout << s << endl;
fs.close();
fs.open("test.txt", ios::in|ios::out|ios::binary);
if (!fs.is_open() || !fs.good())
cerr << "could not open!" << endl;
fs.read(&tmp, 1);
fs.read(&tmp, 1);
//fs.tellg(); //<-- required to fix for old g++?
const char *c = "ah";
fs.write(&c[0], 1);
fs.write(&c[1], 1);
fs.close();
fs.open("test.txt", fstream::in);
fs >> s;
cout << s << endl;
}
In recent g++ versions (at least with 6.2.1), I can just read and then write some bytes without problems - In the example you get the correct output:
blub
blah
Then I compiled the code with g++ 4.7.2 and suddenly the update has no effect, i.e. the second output is still "blub", unless I add fs.tellg() or fs.tellp(). I've found this question, but as I understand, this is a limitation under Windows, but I am working under Linux.
Now I wonder, is this a bug in the old g++ or am I doing it wrong and was just lucky with the modern g++ version, where it just works? Second question, why does asking for the current position fix it?
Thanks in advance!