I have strange behavior in my C ++ program running on a Debian x64 computer.
I am unable to read the file first, and then write a different value, and then read these values. I read a lot of information, including questions about stackoverflow, learned (also through experiments) that I need to change both seekp and seekg, and I will do it. Everything works ... until I read something from the stream. After the read operation, if I search about the beginning of the file, then call tellg (), tellp (), both of them return -1.
Test code:
void testFstreamSeekp() { fstream in("file", ios::in | ios::out); cout << "g: " << in.tellg() << endl; cout << "p: " << in.tellp() << endl; in.seekp(0, ios_base::end); cout << "endp g: " << in.tellg() << endl; cout << "endp p: " << in.tellp() << endl; in.seekp(0, ios_base::end); in.seekg(0, ios_base::end); cout << "end g: " << in.tellg() << endl; cout << "end p: " << in.tellp() << endl; in.seekp(0, ios_base::beg); in.seekg(0, ios_base::beg); cout << "beg g: " << in.tellg() << endl; cout << "beg p: " << in.tellp() << endl; // Everything is fine until here (that is tellp() == 0, tellg() == 0) int a, b; in >> a >> b; cout << "a: " << a << endl << "b: " << b << endl; // tellg() == -1, tellp() == -1 ?????????!!!!!!!!!! cout << "read g: " << in.tellg() << endl; cout << "read p: " << in.tellp() << endl; in.seekp(0, ios_base::beg); in.seekg(0, ios_base::beg); // tellg() == -1, tellp() == -1 ?????????!!!!!!!!!! cout << "beg g: " << in.tellg() << endl; cout << "beg p: " << in.tellp() << endl; }
Can someone tell me what is happening and what can I do to solve the problem?
source share