用c ++将对象写入二进制文件

时间:2016-04-01 10:55:24

标签: c++

当我在C ++中将对象写入二进制文件时,我感到困惑。当我将一个字符串写入文件时,如下所示:

//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();

但它为文件而不是字符串本身写了别的东西(可能是一个指针)。

当我写一个类的对象(有一个字符串成员)时,它起作用了。

// 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;
}

输出正确的信息。

为什么呢?感谢。

2 个答案:

答案 0 :(得分:1)

string对象包含指向实际文本所在的堆的指针。将对象存储到文件时,存储指针但不存储指向的对象。

在第二个示例中,您读取了指向p1到p2中实际char数组的指针,并且由于p1仍然存在,因此您可以看到相同的名称。但是,您仍然遇到同样的问题,实际上并没有将实际可读的字符串存储到文件中。

您不应该使用指向堆到文件的指针来存储对象。您只能通过强制转换将字符串转换为char指针。您应该使用c_str()代替。所以尝试类似的事情:

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

答案 1 :(得分:0)

您正在读取人物对象的内存地址。 Person对象由字符串对象和int对象组成。在程序仍在运行时从内存中读取这些值意味着与通过=运算符复制对象相同。