我使用C++,与2008年的Visual Studio说我有一个结构,像这样:C++阅读结构的领域,直接写入结构到流
struct StructOfInts
{
int a;
int b;
int c;
};
这意味着要读取和写入,如下所示:
void Read(std::istream& is, StructOfInts& myStruct )
{
is.read((char*)&myStruct.a, sizeof myStruct.a);
is.read((char*)&myStruct.b, sizeof myStruct.b);
is.read((char*)&myStruct.c, sizeof myStruct.c);
}
void Write(std::ostream& os, StructOfInts& myStuct)
{
os.write((char*)&myStruct, sizeof myStruct);
}
上述代码在读取或写入文件时会导致某种内存损坏吗?通过内存损坏,我的意思是读取不正确的值。我试图确定正在读入的-1.#QNB值的来源,并且想知道这是否可能是原因。 另外,如果我使用杂注包打包结构,是否有区别?
没有使用>>操作符的任何特定原因? – Borgleader
没有特别的理由。这就是我正在使用的(非常古老的)代码库是如何保持一致性的。 – kushaldsouza
我认为问题出现在这一行:'os.write((char *)&myStruct,sizeof myStruct);'。尝试按元素写入“ostream”元素。因为如果你在64位机器上,可能会有填充,因为“sizeof(int)”将是32位。 –