簡體   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