我想将文件读入结构或类,但经过一番阅读后,我发现这样做不是一个好主意:
int MyClass::loadFile( const char *filePath ) {
ifstream file ( filePath, ios::in | ios::binary );
file.read ((char*)this, 18);
file.close();
return 0;
}
我猜如果我想从一个结构/类中写一个文件,这也不是 kosher:
void MyClass::writeFile( string fileName ) {
ofstream file( fileName, ofstream::binary );
file.write((char*)this, 18);
file.close();
}
听起来我不想这样做的原因是因为即使我的结构的数据成员加起来最多 18 个字节,其中一些可能会在内存中填充额外的字节。有没有更正确/优雅的方式将文件放入这样的类/结构中?