问题
struct DATAs
{
char data1;
short data2;
short data3;
float data4;
int data5;
short data6;
unsigned short data7;
short data8;
char data9;
};
void fixFile(char* filename)
{
std::ifstream InputFile;
InputFile.open(filename, std::ios::binary);
DATAs FileDatas;
InputFile.read(reinterpret_cast<char*>(&FileDatas), sizeof(FileDatas));
}
Why do I need to use "reinterpret_cast" for the reading instead of
"InputFile.read(&FileDatas, sizeof(FileDatas))" ?
回答1:
The type of the first argument to std::ifstream::read()
is char*
. A pointer of type DATAs*
is not automatically cast to char*
in C++. Hence, you need to use reinterpret_cast
.
回答2:
This code is a undefined behavior. Class fields can be aligned to some specific address to improve performance.
Also sizes of types are not well defined, so if you compile your program for 32 or 64 bits you can have different results.
And there is also an endian issue.
It is recommended do not read data using this approach.
来源:https://stackoverflow.com/questions/49565933/using-reinterpret-cast-to-read-file-into-structure