简体   繁体   English

C ++将结构附加到二进制文件中

[英]c++ append a struct into a binary file

I have my struct: 我有我的结构:

struct a
{
  int    x;
  float  f;
  double d;
  char   c;
  char   s[50];
};

and I wish append each time into my timer schedule into a binary file. 我希望每次都将其时间表添加到二进制文件中。

// declaration
std::ofstream outFile;

// constructor:
outFile.open( "save.dat", ios::app );

// tick:
outFile << a << endl;

but inside the save.dat appears only this: 但是在save.dat内部仅显示以下内容:

0C3A0000..0C3A0000..0C3A0000..0C3A0000..0C3A0000..0C3A0000..0C3A0000..0C3A0000..0C3A0000..

thanks in advance 提前致谢

What you're currently doing is writing the address of the struct definition. 您当前正在做的是写结构定义的地址。
What you want to do is use ostream::write 您要做的是使用ostream :: write

outfile.write(reinterpret_cast<char*>(&myStruct), sizeof(a));

This will work as long as your struct is a POD (Plain Old Data) type (which your example is). 只要您的结构是POD(普通旧数据)类型(您的示例是这种类型),它就可以工作。 POD type means that all members are of fixed size. POD类型表示所有成员的大小都是固定的。

If you on the other hand have variable sized members then you would need to write out each member one by one. 另一方面,如果您具有可变大小的成员,则需要逐个写出每个成员。

A sensible way to serialize custom objects is to overload your own output stream operator: 序列化自定义对象的明智方法是重载您自己的输出流运算符:

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;

This is still platform-dependent, so to be a bit safer, you should probably use fixed-width data types like int32_t etc. 这仍然依赖于平台,因此为了更加安全起见,您可能应该使用固定宽度的数据类型,例如int32_t等。

It might also not be the best idea semantically to use << for binary output, since it's often used for formatted output. 从语义上来说,将<<用于二进制输出也不是最好的主意,因为它经常用于格式化输出。 Perhaps a slightly safer method would be to write a function void serialize(const a &, std::ostream &); 也许更安全的方法是编写一个函数void serialize(const a &, std::ostream &);

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

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