[英]c++ append a struct into a binary file
我有我的結構:
struct a
{
int x;
float f;
double d;
char c;
char s[50];
};
我希望每次都將其時間表添加到二進制文件中。
// declaration
std::ofstream outFile;
// constructor:
outFile.open( "save.dat", ios::app );
// tick:
outFile << a << endl;
但是在save.dat內部僅顯示以下內容:
0C3A0000..0C3A0000..0C3A0000..0C3A0000..0C3A0000..0C3A0000..0C3A0000..0C3A0000..0C3A0000..
提前致謝
您當前正在做的是寫結構定義的地址。
您要做的是使用ostream :: write
outfile.write(reinterpret_cast<char*>(&myStruct), sizeof(a));
只要您的結構是POD(普通舊數據)類型(您的示例是這種類型),它就可以工作。 POD類型表示所有成員的大小都是固定的。
另一方面,如果您具有可變大小的成員,則需要逐個寫出每個成員。
序列化自定義對象的明智方法是重載您自己的輸出流運算符:
std::ostream & operator<<(std::ostream & o, const a & x)
{
o.write(reinterpret_cast<char*>(&x.x), sizeof(int));
o.write(reinterpret_cast<char*>(&x.f), sizeof(float));
/* ... */
return o;
}
a x;
std::ofstream ofile("myfile.bin", std::ios::binary | std::ios::app);
ofile << a;
這仍然依賴於平台,因此為了更加安全起見,您可能應該使用固定寬度的數據類型,例如int32_t
等。
從語義上來說,將<<
用於二進制輸出也不是最好的主意,因為它經常用於格式化輸出。 也許更安全的方法是編寫一個函數void serialize(const a &, std::ostream &);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.