[英]c++ read file in binary mode into object failed but is ok in stdin and file read in text
在標准輸入中讀取或在文本中讀取文件的方法已被證明是正確的。 二進制讀取中的 go 錯誤。
這里我有一個名為Laptop的class和一個名為laptop.txt的文件,由后面的代碼編寫。 我已經重新加載了>>
和<<
using namespace std;
class Laptop
{
private:
string brand;
string cpu;
string ram;
string disk;
int reserve;
public:
Laptop() {}
Laptop(string aBrand, string aCpu, string aRam, string aDisk, int aReserve)
{
this->brand = aBrand;
this->cpu = aCpu;
this->ram = aRam;
this->disk = aDisk;
this->reserve = aReserve;
}
friend ostream &operator<<(ostream &os, const Laptop &laptop)
{
os << laptop.brand << " " << laptop.cpu
<< " " << laptop.ram << " " << laptop.disk << " " << laptop.reserve;
return os;
}
friend istream &operator>>(istream &is, Laptop &laptop)
{
is >> laptop.brand >> laptop.cpu >> laptop.ram >> laptop.disk >> laptop.reserve;
return is;
}
};
int main()
{
fstream file("laptop.txt", ios::out | ios::binary);
vector<Laptop> laptops;
Laptop aLaptop;
for (int i = 0; i < 5; i++)
{
cin >> aLaptop;
laptops.push_back(aLaptop);
}
for (vector<Laptop>::iterator i = laptops.begin(); i != laptops.end(); i++)
{
file.write((char *)(&i), sizeof(*i));
}
return 0;
}
但是在二進制讀取中,事情並沒有 go 正確。 當我嘗試將 aLaptop 推送到向量時,出現了 class 筆記本電腦的異常。 我真的不知道為什么。 這太糟糕了。
int main()
{
fstream file("laptop.txt", ios::in);
vector<Laptop> laptops;
Laptop aLaptop;
while (file.peek() != EOF)
{
file.read((char *)(&aLaptop), sizeof(aLaptop));
laptops.push_back(aLaptop);
}
return 0;
}
您有一個 class 由四個字符串和一個 int 組成,您將指向它的指針轉換為字符指針並嘗試以二進制模式從文本文件中讀取它。
字符串由長度和指針組成。 指針指向包含字符的可變大小的 memory 塊。 sizeof
返回長度和指針的大小,但不返回字符塊。 因此,當您讀取文件時,您會獲得長度和指針,但不會獲得組成字符串的字符。 因此指針指向垃圾。
正確的方法是:
只要 integer 是二進制寫入的,就可以從二進制文件中讀取 integer。 為了可移植性,最好以一致的字節順序讀取和寫入整數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.