c++ i get duplicated info when i read a binary file

304 views Asked by At

Im writing a vector of size three and when i read i get a vector of size 4 with the last index being a duplicate of the index 2.

Heres my code.

void IOManager::WriteBin(const string &filename, vector<userRank> highScorers, int rank) {

    ofstream fsalida(filename, ios::out | ios::binary); 

    if (fsalida.is_open())
    {
        for (int i = 0; i < highScorers.size();i++) {
            fsalida.write(reinterpret_cast<char*>(&highScorers[i]), sizeof(highScorers[i]));

        }
        //highScorers.size() is 3
        fsalida.close();      

    }else cout << "Unable to open file for writing\n";
}

vector<userRank> IOManager::ReadBin(const string &filename) {

    ifstream fentrada(filename, ios::in | ios::binary); 

    if (fentrada.is_open())
    {

        vector<userRank>bestPlayers;

        for (int i = 0; fentrada.good(); i++) {
            userRank tempUser;
            fentrada.read(reinterpret_cast<char*>(&tempUser), sizeof(tempUser));
            bestPlayers.push_back(tempUser);

        }
        //bestPlayers.size() is 4!!!!!! Im losing my mind
        fentrada.close();

        return bestPlayers;

    }
    else cout << "Unable to open file for reading\n";   

}

Here's my UserRank struct

struct userRank
{
    char userName [5];
    int score;  
};

A wild userRank apperars for some reason, does anybody know why?

1

There are 1 answers

1
Thomas Matthews On BEST ANSWER

I suggest reorganizing the read function:

userRank tempUser;
for (int i = 0;
     fentrada.read(reinterpret_cast<char*>(&tempUser), sizeof(tempUser));
     i++)
{
    bestPlayers.push_back(tempUser);
}

Search the internet for "stackoverflow c++ why eof in while is bad".