简体   繁体   中英

write an object to a file using pointer in c++

I have this object ob, which I am writing to the file using the pointer to that object. But it does not seem to be working.

class A
{
public:
    int Arr[10];
    A();
};
A::A()
{
    for(int i=0;i<10;i++)
        Arr[i] = 0;
}
A obj;
int main(int argc, char *argv[])
{
    A *ptr = &obj, temp;
    obj.Arr[0] = 1;

    fstream fp("temp", ios::in|ios::binary|ios::out);
    fp.write((char *)ptr, sizeof(*ptr));
    fp.close();

    fp.open("temp", ios::in|ios::binary|ios::out);
    fp.read((char *)&temp, sizeof(temp));
    for(int i=0;i<10;i++)
        cout<<temp.Arr[i]<<" ";
    fp.close();
    return 0;
}

Output :

0 0 0 0 0 0 0 0 0 0

Expected output :

1 0 0 0 0 0 0 0 0 0

How do I write the object directly using the pointer. Also is there any way to directly read the contents in the pointer itself?

You open the file for reading ( std::ios::in ) both times. When you open the file for reading, it must exist or else opening it will fail, which means that your first open doesn't succeed, so the file isn't created.

Your second open will also fail because of the missing file.

Therefore, always check that opening a file actually succeeds and use the proper openmode:

#include <fstream>
#include <iostream>
class A {
public:
    int Arr[10]{};

    void print() const {
        for(int val : Arr) std::cout << val << ' ';
        std::cout << '\n';
    }
};

int main() {
    A obj;
    A temp;
    obj.Arr[0] = 1;

    // open file for writing and check that opening succeeded
    if(std::ofstream fp("temp", std::ios::binary); fp) {
        obj.print();
        fp.write(reinterpret_cast<const char*>(&obj), sizeof(obj));
    }

    // open the file for reading and check that opening succeeded
    if(std::ifstream fp("temp", std::ios::binary); fp) {
        fp.read(reinterpret_cast<char*>(&temp), sizeof(temp));
        temp.print();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM