Explain why seekg and seekp don't work

Previously, these functions were not required. The file was opened for reading, the data was written to the vector, then the record was deleted in the vector and the file was overwritten.

The file is now open for reading, writing, and re-writing. And to perform the algorithm described above, you need to use the functions seekg, seekp, to set the cursor to the desired position. Here's the method, what's wrong ?

void DBTextFileAdapter::remove(string login)
{
    file->seekg(ios_base::beg);
    while (*file >> user._login >> user._password)
    {
        container.push_back(user);
    }
    for (vector<User>::iterator it = container.begin(); it != container.end(); ++it)
    {
        if (it->_login == login) //находим запись
        {
            container.erase(it); //удаляем запись
            break;
        }
    }
    file->seekp(ios_base::beg); //это не работает
    for (vector<User>::iterator i = container.begin(); i != container.end(); ++i)
    {
        *file << i->_login << " " << i->_password << endl; //перезапись
    }
    container.clear(); 
}
Author: alex-rudenkiy, 2016-04-21

1 answers

First, call

file->seekp(ios_base::beg);

Is not formally legal. This function has two versions

basic_ostream& seekp( pos_type pos );
basic_ostream& seekp( off_type off, std::ios_base::seekdir dir);

ios_base::beg - this is a value of type ios_base::seekdir, which can only be the second parameter of the second version of the method. You put it in the first parameter, thus calling the first version of the method, but giving it the value ios_base::beg as the absolute position. It turns out to be convertible to the pos_type type, i.e. the code is compiled, but what exactly is it equal to as a result - who is it? he knows...

The same problem occurs with

file->seekg(ios_base::beg);

Correct

file->seekg(0, ios_base::beg);
...
file->seekp(0, ios_base::beg);

Or just

file->seekg(0);
...
file->seekp(0);

Second, the read loop ended with the thread in the fail() state (failbit and eofbit were set). Until the fail() state is reset, i.e. until the thread is put in the good() state, it will ignore all I / O operations. Do

file->clear();

Before proceeding to the record and only after that already seekp, etc.

 5
Author: AnT, 2016-04-21 21:56:43