c++ reading and writing objects to binary files

2019-08-02 15:29发布

问题:

I'm trying to read an array object (Array is a class I've made using read and write functions to read and write from binary files. So far the write functions works but it won't read from the file properly for some reason. This is the write function :

void writeToBinFile(const char* path) const
    {
        ofstream ofs(path, ios_base::out | ios_base::binary | ios_base::trunc);
        if (ofs.is_open())
        {
            ofs.write((char*)this, sizeof(Array<T>));
        }
    }

This is the read function :

void readFromBinFile(const char* path)
{
    ifstream ifs(path, ios_base::in | ios_base::binary);
    if (ifs.is_open())
    {
        ifs.read((char*)this, sizeof(Array<T>));
    }
}

those are the class fields :

T* m_data;
unsigned int m_size;
unsigned int m_elementCount;

I'm using the following code to write and then read :

Array<int> arr3(5);
arr3[0] = 38;
arr3[1] = 22;
arr3[2] = 55;
arr3[3] = 7;
arr3[4] = 94;
arr3.writeToBinFile("binfile.bin");
Array<int> arr4(5);
arr4.readFromBinFile("binfile.bin");
for (unsigned int i = 0; i < arr4.elementCount(); i++)
{
    cout << "arr4[" << i << "] = " << arr4[i] << endl;
}

and it just skips the for loop like there're no elements in the array at all