Using reinterpret_cast to read file into structure

生来就可爱ヽ(ⅴ<●) 提交于 2021-02-20 04:58:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!