我想使用ifstream和ofstream序列化一个普通的旧数据结构,我无法让它工作。然后,我试图将我的问题简化为只是一个char和int的超基本序列化,甚至没有工作。很明显,我错过了核心基础层面的一些东西。无法使用ifstream和ofstream序列化二进制数据
对于基本结构:
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”在顶部,所以也许它正在并将其与placement new
在最后只是一个问题吗?该安置新我结束了同值的SerializeTestStruct
后:0,0。
为什么不在流中使用插入/提取操作符? – 2011-04-18 19:31:22
如果允许使用其他库,这已经在C++中解决了。你这样做只是为了让自己受益? – wheaties 2011-04-18 19:37:46
@arasmussen:插入/提取操作符用于格式化文本I/O。他想要无格式的二进制I/O。 – 2011-04-18 19:41:09