使用reinterpret_cast将文件读入结构 [英] Using reinterpret_cast to read file into structure

查看:95
本文介绍了使用reinterpret_cast将文件读入结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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));
}

为什么我需要使用"reinterpret_cast"代替

Why do I need to use "reinterpret_cast" for the reading instead of

"InputFile.read(& FileDatas,sizeof(FileDatas))"?

"InputFile.read(&FileDatas, sizeof(FileDatas))" ?

推荐答案

std :: ifstream :: read()的第一个参数的类型为 char * .类型为 DATAs * 的指针在C ++中不会自动转换为 char * .因此,您需要使用 reinterpret_cast .

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.

这篇关于使用reinterpret_cast将文件读入结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆