简体   繁体   中英

Using reinterpret_cast to read file into structure

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))" ?

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM