Program stopped working when trying to file.read() to a new variable

52 views Asked by At

Ok so i have this code i just want to write my struct to the file and then read using another variable because i want to return a vector of userRankings when reading.

Here'es my write/read

void IOManager::WriteBin(const string &filename, userRank u1) {

    ofstream fsalida(filename, ios::out | ios::binary); //obrim un archiu per escriure en binari i de tipo append per poder escriure al final i no xafar-ho tot cada cop

    if (fsalida.is_open())
    {
        fsalida.write(reinterpret_cast<char*>(&u1), sizeof(u1));
        fsalida.close();


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

}

void IOManager::ReadBin(const string &filename) {



    ifstream fentrada(filename, ios::in | ios::binary); //ate per posarnos al final del archiu i tenir el tamany

    if (fentrada.is_open())
    {   
        userRank tempUser;
        fentrada.read(reinterpret_cast<char*>(&tempUser), sizeof(tempUser));
        fentrada.close();

        cout << sizeof(tempUser) << endl;

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

}

And my userRank:

struct userRank
{
    std::string userName;
    int score;
};

The line that fails is fentrada.read(reinterpret_cast(&tempUser), sizeof(tempUser));

Please help, this seems to work with ints, chars, etc but not with strings and complex types, does anybody know why?

1

There are 1 answers

1
François Andrieux On BEST ANSWER

Using reinterpret_cast in that way is dangerous and may break for many reasons. In this particular case, the reason it doesn't work is because struct userRank contains std::string which is not a POD type (plain old data type). That means you can't simply set it's bits and expect to get the right state. std::string contains a pointer to allocated memory. Setting the bits of a std::string doesn't allocate the memory it is expecting to find at that pointer's address.

The quick fix (relatively speaking) is to use std::array instead of std::string to store the userName. The right fix is to write functions that will read/write the structure's state to/from the file member by member.