Seekp and seekg do not work with fstream

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?

+4
source share
1 answer

For fstream ( std::basic_filebuf ), the position of one file is moved with both seekp() and seekg()

Tracking put and get positions is not possible independently.

The class std::basic_filebuf contains one file position

ยง 27.9.1.1

  • The basic_filebuf class associates both an input sequence and an output sequence with a file.

  • The restrictions on reading and writing the sequence controlled by the object of the basic_filebuf class are the same as for reading and writing with the F files of Standard C.

  • In particular:

    • If the file is not open for reading, the input sequence cannot be read.
    • If the file is not open for writing, the output sequence cannot be written.
    • The joint file position is saved for both the input sequence and the output sequence.
+2
source

Source: https://habr.com/ru/post/1496579/


All Articles