c++ reading and writing objects to binary files

白昼怎懂夜的黑 提交于 2019-12-11 08:12:50

问题


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

来源:https://stackoverflow.com/questions/26196682/c-reading-and-writing-objects-to-binary-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!