如何解决使用ifstream和ofstream序列化二进制数据时遇到问题
| 我正在尝试使用ifstream和ofstream序列化一个普通的旧数据结构,但我无法使其正常工作。然后,我试图将我的问题简化为仅是char和int的超基本序列化,甚至没有用。显然,我在核心基本层面上缺少某些东西。 对于基本结构:struct SerializeTestStruct
{
char mCharVal;
unsigned int mIntVal;
void Serialize(std::ofstream& ofs);
};
具有序列化功能:
void SerializeTestStruct::Serialize(std::ofstream& ofs)
{
bool isError = (false == ofs.good());
if (false == isError)
{
ofs.write((char*)&mCharVal,sizeof(mCharVal));
ofs.write((char*)&mIntVal,sizeof(mIntVal));
}
}
为什么在以下简短程序中失败了?
//ultra basic serialization test.
SerializeTestStruct* testStruct = new SerializeTestStruct();
testStruct->mCharVal = \'y\';
testStruct->mIntVal = 9;
//write
std::string testFileName = \"test.bin\";
std::ofstream fileOut(testFileName.data());
fileOut.open(testFileName.data(),std::ofstream::binary|std::ofstream::out);
fileOut.clear();
testStruct->Serialize(fileOut);
fileOut.flush();
fileOut.close();
delete testStruct;
//read
char * memblock;
std::ifstream fileIn (testFileName.data(),std::ifstream::in|std::ifstream::binary);
if (fileIn.is_open())
{
// get length of file:
fileIn.seekg (0,std::ifstream::end);
int length = fileIn.tellg();
fileIn.seekg (0,std::ifstream::beg);
// allocate memory:
memblock = new char [length];
fileIn.read(memblock,length);
fileIn.close();
// read data as a block:
SerializeTestStruct* testStruct2 = new(memblock) SerializeTestStruct();
delete[] testStruct2;
}
当我遍历代码时,我注意到memblock
的顶部带有\“ y \”,所以也许它可以正常工作,而end4ѭ的末尾只是一个问题?新的放置之后,我得到一个SerializeTestStruct
,值:0、0。解决方法
这是您的内容应如何阅读:
#include <fstream>
#include <string>
#include <stdexcept>
struct SerializeTestStruct
{
char mCharVal;
unsigned int mIntVal;
void Serialize(::std::ostream &os);
static SerializeTestStruct Deserialize(::std::istream &is);
};
void SerializeTestStruct::Serialize(std::ostream &os)
{
if (os.good())
{
os.write((char*)&mCharVal,sizeof(mCharVal));
os.write((char*)&mIntVal,sizeof(mIntVal));
}
}
SerializeTestStruct SerializeTestStruct::Deserialize(std::istream &is)
{
SerializeTestStruct retval;
if (is.good())
{
is.read((char*)&retval.mCharVal,sizeof(retval.mCharVal));
is.read((char*)&retval.mIntVal,sizeof(retval.mIntVal));
}
if (is.fail()) {
throw ::std::runtime_error(\"failed to read full struct\");
}
return retval;
}
int main(int argc,const char *argv[])
{
//ultra basic serialization test.
// setup
const ::std::string testFileName = \"test.bin\";
// write
{
SerializeTestStruct testStruct;
testStruct.mCharVal = \'y\';
testStruct.mIntVal = 9;
::std::ofstream fileOut(testFileName.c_str());
fileOut.open(testFileName.c_str(),std::ofstream::binary|std::ofstream::out);
fileOut.clear();
testStruct.Serialize(fileOut);
}
// read
{
::std::ifstream fileIn (testFileName.c_str(),std::ifstream::in|std::ifstream::binary);
if (fileIn.is_open())
{
SerializeTestStruct testStruct = \\
SerializeTestStruct::Deserialize(fileIn);
::std::cout << \"testStruct.mCharVal == \'\" << testStruct.mCharVal
<< \"\' && testStruct.mIntVal == \" << testStruct.mIntVal
<< \'\\n\';
}
}
return 0;
}
样式问题:
如果可以帮助,请勿使用ѭ7进行创建。堆栈分配的对象通常是您想要的,并且比从堆分配的任意生存期对象要容易得多。如果您确实使用new
,请考虑使用某种智能指针类型来帮助您管理生命周期。
序列化和反序列化代码应匹配,以便可以一起检查和更改它们。这使得此类代码的维护更加容易。
依靠C ++可以使用析构函数为您清理内容,这就是它们的用途。这意味着如果所用变量的范围相对有限,则使基本块包含代码的一部分。
不必使用标志。
错误...
不要使用::std::string
的data
成员函数。
使用位置ѭ7和那个内存块实在是一个坏主意,因为它非常复杂。而且,如果您确实使用过它,那么您将不会像以前那样使用数组删除。最后,由于稍后说明的原因,它仍然无法正常工作。
不要在Serialize
函数采用的类型中使用ofstream
,因为它是派生类,不需要您的功能。除非有非常特殊的理由,否则应始终在具有所需功能的层次结构中使用最基本的类。 Serialize
与with15ѭ基类的功能配合良好,请改用该类型。
您的结构的磁盘上布局与内存中的布局不匹配,因此您的放置新技术注定会失败。通常,如果具有serialize
函数,则需要匹配的deserialize
函数。
这是您的内存布局问题的进一步说明。在基于x86_64的Linux机器上的内存中的结构如下所示:
+------------+-----------+
|Byte number | contents |
+============+===========+
| 0 | 0x79 |
| | (aka \'y\') |
+------------+-----------+
| 1 | padding |
+------------+-----------+
| 3 | padding |
+------------+-----------+
| 4 | padding |
+------------+-----------+
| 5 | 9 |
+------------+-----------+
| 6 | 0 |
+------------+-----------+
| 7 | 0 |
+------------+-----------+
| 8 | 0 |
+------------+-----------+
padding
节的内容未定义,但通常为0
。但这并不重要,因为该空间从未使用过,仅存在,因此对后面的ѭ21的访问位于有效的4字节边界上。
磁盘上结构的大小为5个字节,并且完全缺少填充部分。因此,这意味着当您将其读入内存时,它根本不会与内存结构完全对齐,并且访问它可能会导致某种可怕的问题。
第一条规则,如果需要serialize
函数,则需要deserialize
函数。第二条规则,除非您真的很清楚自己在做什么,否则不要将原始内存转储到文件中。在许多情况下,这都可以正常工作,但是在某些重要情况下,它将无法工作。并且,除非您知道什么有效,什么无效,什么时候该有效或不该有效,否则您最终将获得在某些测试情况下似乎可以正常工作的代码,但是当您尝试使用它时却惨败在真实的系统中。
我的代码仍然会将内存转储到文件中。只要您使用与编写时使用相同版本的编译器编译的代码在完全相同的体系结构和平台上重新读取结果,它就应该起作用。一旦这些变量之一改变,所有的赌注都将关闭。,bool isError = (false == ofs.good());
if (false == isError)
{
ofs.write((char*)&mCharVal,sizeof(mCharVal));
ofs.write((char*)&mIntVal,sizeof(mIntVal));
}
改成
if ( ofs.good() )
{
ofs.write((char*)&mCharVal,sizeof(mIntVal));
}
我会做:
ostream & operator << ( ostream &os,const SerializeTestStruct &mystruct )
{
if ( ofs.good() )
{
os.write((char*)&mystruct.mCharVal,sizeof(mCharVal));
os.write((char*)&mystruct.mIntVal,sizeof(mIntVal));
}
return os;
}
,问题在这里:
SerializeTestStruct* testStruct2 = new(memblock) SerializeTestStruct();
这将在先前分配的内存中构造类型为“ 5”的值初始化对象。由于POD类型的值初始化是零初始化,因此它将用零填充memblock
(更多信息)。
这是您的代码的快速修复方法:
SerializeTestStruct* testStruct2 = new SerializeTestStruct;
fileIn.read( (char*)&testStruct2->mCharVal,sizeof(testStruct2->mCharVal) );
fileIn.read( (char*)&testStruct2->mIntVal,sizeof(testStruct2->mIntVal) );
fileIn.close();
// do some with testStruct2
// ...
delete testStruct2;
,在我看来,您需要允许序列化到缓冲区而不是直接序列到流。写入缓冲区允许嵌套或继承的类写入内存,然后可以将整个缓冲区写入流。将点点滴滴写入流中效率不高。
在停止将二进制数据写入流之前,我构思了以下内容:
struct Serialization_Interface
{
//! Returns size occupied on a stream.
/*! Note: size on the platform may be different.
* This method is used to allocate memory.
*/
virtual size_t size_on_stream(void) const = 0;
//! Stores the fields of the object to the given pointer.
/*! Pointer is incremented by the size on the stream.
*/
virtual void store_to_buffer(unsigned char *& p_buffer) const = 0;
//! Loads the object\'s fields from the buffer,advancing the pointer.
virtual void load_from_buffer(const unsigned char *& p_buffer) = 0;
};
struct Serialize_Test_Structure
: Serialization_Interface
{
char mCharVal;
int mIntVal;
size_t size_on_stream(void) const
{
return sizeof(mCharVal) + sizeof(mIntVal);
}
void store_to_buffer(unsigned char *& p_buffer) const
{
*p_buffer++ = mCharVal;
((int&)(*p_buffer)) = mIntVal;
p_buffer += sizeof(mIntVal);
return;
}
void load_from_buffer(const unsigned char *& p_buffer)
{
mCharVal = *p_buffer++;
mIntVal = (const int&)(*p_buffer);
p_buffer += sizeof(mIntVal);
return;
}
};
int main(void)
{
struct Serialize_Test_Struct myStruct;
myStruct.mCharVal = \'G\';
myStruct.mIntVal = 42;
// Allocate a buffer:
unsigned char * buffer = new unsigned char[](myStruct.size_on_stream());
// Create output file.
std::ofstream outfile(\"data.bin\");
// Does your design support this concept?
unsigned char * p_buffer = buffer;
myStruct.store_to_buffer(p_buffer);
outfile.write((char *) buffer,myStruct.size_on_stream());
outfile.close();
return 0;
}
我停止将二进制数据写入流以支持文本数据,因为文本数据不必担心Endianess或接收平台接受哪种IEEE浮点格式。,我是唯一发现这完全不透明的人吗?
bool isError = (false == ofs.good());
if (false == isError) {
// stuff
}
为什么不:
if ( ofs ) {
// stuff
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。