Using reinterpret_cast to read file into structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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));
}


Can someone explain clearly why I need to use "reinterpret_cast" for the reading instead of "InputFile.read(&FileDatas, sizeof(FileDatas))" ?

The structure of the file are known and tested, I just copied the struct from a similar program's source code, there I found this cast method so that is why I am asking.
Last edited on
Because std::istream::read() expects a char * as its first parameter. If it expected void * there would be no problem.

It's worth noting that your code may behave incorrectly if the CPU and the file being read don't agree on endianness.
Thank you ! and can you tell me what exactly the "reinterpret_cast" doing ? I know its converts the structure into char, but it will be converted back when the read process finished ?
Last edited on
No, it's not converting the structure, it's telling the compiler "I know you think this pointer points to DATAs. Ignore that for a moment and assume it really points to a char". The cast produces no code, it only affects how the compiler checks types.
Ah, now I get it. Thank you again !
Topic archived. No new replies allowed.