C 结构序列化
C++ struct serialization
我正在实现一个数据缓冲区,该数据缓冲区从一个应用程序中接收带有过程调用的音频数据软件包(无需在同一机器上运行的两个应用程序),然后将其放入一个结构中,并将其写入一个映射的文件。
因此,Writer应用程序可以调用我的应用程序的过程,该过程将像void writeData (DataItem data, Timestamp ts)
一样smth,每秒大约15次,每个数据项大小2MB。
我的应用程序应将数据存储到
之类的结构中Struct DataItem
{
long id;
... Data;
Time insertTime;
}
并将其写入文件以将来阅读目的。
因此,由于很难将结构保存到文件中,因此我认为(?)需要将其写为二进制文件。因此,我不确定我是否需要使用任何类型的序列化(例如boost serialization
)?
我不知道如何将此数据对齐以获取内存映射文件,以及如何从文件中重新构造数据。
我搜索互联网,但找不到太多代码示例。和示例代码将被贴上杂项。
顺便说一下,我使用Windows 7 X64嵌入式和Visual Studio 2008。
谢谢...
序列化的常见C 方法是:
struct myStruct
{
int IntData;
float FloatData;
std::string StringData;
};
std::ostream& operator<<(std::ostream &os, const myStruct &myThing)
{
os
<< myThing.IntData << " "
<< myThing.FloatData << " "
<< myThing.StringData << " "
;
return os;
}
std::istream& operator>>(std::istream &is, myStruct &myThing)
{
is
>> myThing.IntData
>> myThing.FloatData
>> myThing.StringData;
return is;
}
void WriteThing()
{
myStruct myThing;
myThing.IntData = 42;
myThing.FloatData = 0.123;
myThing.StringData = "My_String_Test";
std::ofstream outFile;
outFile.open("myFile.txt");
outFile << myThing;
}
void ReadThing()
{
myStruct myThing;
std::ifstream inFile;
inFile.open("myFile.txt");
inFile >> myThing;
}
请注意:
- std :: String定义运营商&lt;&lt;>>。这些会在上面的代码。
- 流将将白空间字符视为定界符。用空白存储字符串将需要额外的处理
- 如果您打算通过更新来保留数据软件,您必须实现某种文件版本
- 请参阅Fstream的文档,以了解如何移动文件指针在一个大文件上使用seek等。
使用boost ::序列化与文本存档。
是解决平台独立性的最"标准"方式。
可选,您可以在其顶部设置GZIP压缩。
您确定要问C 而不是C#吗?您的代码示例看起来像C#
在C 中,如果您的struct格式不会更改,则可以将数组写入磁盘。
这是您要求的示例,但这实际上是C 101东西
FILE* output=fopen ("myfile", "wb");
fwrite (array, sizeof (mystruct), number_of_elements_in_array, output);
fclose (output);
相关文章:
- 如何在C++中序列化结构数据
- 如何使用boost::具有嵌套结构和最小代码更改的序列化
- 如何在 boost::asio 中将打包的结构作为消息传递?(无序列化)
- 使用指向 struc 的指针序列化结构
- C++ 提升 - 包含类层次结构对象的类的序列化
- 如何从平面缓冲区中反序列化联合结构的 void* 值的大小
- 将载体和cv :: mat to Disk的存储结构 - C 中的数据序列化
- 序列化没有"save"方法的大型结构
- 在 C# 中序列化这些值以在C++中作为已知结构正确读取时遇到问题
- 无序列图会创建一个零初始化结构吗?
- 如何在结构中序列化unique_ptr<char[]>
- 我的数据结构的最佳序列化方法
- 分段错误:C++中的结构序列化和 MPI 数据传输
- 跳过层次结构中的中间类,并使用boost ::序列化
- Boost::序列化存储结构时的堆栈溢出错误
- C 使用谷物序列化结构的静态阵列
- 具有3字节块的序列化C 结构
- 序列化结构以归档,并用字符串再次对其进行启用
- 序列化结构
- 序列化结构的STL映射