简体   繁体   中英

write an object to a binary file in c++

I get confused when I wrote an object to a binary file in C++. When I wrote a string to a file, like this:

//write a string to a binary file
ofstream ofs("Test.txt", ofstream::binary | ofstream::app);
string foo = "This is a long .... string."
ofs.write((char*)&foo, sizeof(foo));
ofs.close();

But it wrote something else(maybe a pointer) to the file rather than the string itself.

When I wrote an object of a class(which has a string member), it worked.

// a simple class
class Person {
public:
    Person() = default;
    Person(std::string name, int old) : fullName(name), age(old) {}
    std::string getName() const { return this->fullName; }
    int getAge() const { return this->ID; }

private:
    string fullName;
    int age;
};

int main()
{
    std::ofstream ofs("Test.txt", std::ofstream::binary | std::ofstream::app);
    Person p1("lifeisamoive", 1234);
    ofs.write((char*)&p1, sizeof(Person));
    ofs.close();

    Person *p2 = new Person();
    std::ifstream ifs("Test.txt", std::ifstream::binary);
    //output the right information
    while(ifs.read((char*)p2, sizeof(Person)))
        std::cout << p2->getName() << " " << p2->getAge() << std::endl;
    else
        std::cout << "Fail" << std::endl;
    ifs.close();
    return 0;
}

It output the right information.

Why? Thanks.

string object contains pointers to heap where the actual text remains. When you store the object to a file, you store the pointers but not what they point to.

In the second example you read the pointer to the actual char array in p1 to p2 and since p1 still exists, you can see the same name. However, you still have the same problem, you did not actually store the actual readable string to a file.

You should not store objects with pointers to heap to file. You can not convert string to char pointer just by casting. You should use c_str() instead. So try something like:

ofstream ofs("Test.txt", ofstream::binary | ofstream::app);
string foo = "This is a long .... string."
ofs.write(foo.c_str(), foo.size());
ofs.close();

You are reading the memory address of the person object. The Person object consist of a string object and an int object. Reading these values from memory while the program is still running means the same as copying the object via an = operator.

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