1

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

3
  • In general, this approach of reading and writing objects blindly is going to get you in trouble. If your object has pointers (including pointers created as part of the object), this is not going to work. You really needs to save the elements/ Oct 4, 2014 at 20:09
  • Your read/write functions look like they'll only read/write the member fields of your Array class, not the elements of the array itself (i.e. any dynamically allocated data). Oct 4, 2014 at 20:11
  • @user3344003 & Jonathan Potter I see, I had made another version where it saves the elements rather but I had problems with reading again. I'll open a new question with the other version
    – dikson231
    Oct 4, 2014 at 20:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.