繁体   English   中英

将对象写入 C++ 中的二进制文件

[英]write an object to a binary file in 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;
}

它输出正确的信息。

为什么? 谢谢。

字符串对象包含指向实际文本所在的堆的指针。 当您将对象存储到文件时,您存储的是指针,而不是它们指向的内容。

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

您不应该存储带有指向文件的堆指针的对象。 您不能仅通过强制转换将字符串转换为字符指针。 您应该使用 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();

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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