c++ - `fout.write( reinterpret_cast<const char*>(&e), sizeof(e) );` 为什么在这里转换成 `const char*` ?

标签 c++ binaryfiles file-handling reinterpret-cast

代码

#include <iostream>
#include <fstream>

struct emp
        {
            char name[20];
            int age;
        };

int main()
{
    emp e1={"Abhishek", 22},e2;
    
    std::ofstream fout;
    fout.open("vicky.dat", std::ios::out | std::ios::binary);
    fout.write(reinterpret_cast<const char*>(&e1),24);
    fout.close();

    std::ifstream fin;
    fin.open("vicky.dat", std::ios::in | std::ios::binary);
    fin.read(reinterpret_cast<char*>(&e2),24);
    fin.close();

    std::cout<<e2.name<<" "<<e2.age<<"\n";

    return 0;
}

为什么需要对writeread函数的第一个参数进行reinterpret_cast

为什么我们在 write 中将 emp 类型的地址特别转换为 const char*char* code>分别读取函数?

最佳答案

Why it is necessary to do reinterpret_cast with 1st argument of write and read function ?

因为 write() 的第一个参数是 const char*read() 的第一个参数是 char* .

why we casting address of type emp particularly to const char* and char* in write and read function respectively ?

您可以将两者都转换到 char*在你的情况下 - 但是,在 write 的情况下,它不需要可变对象,因为它不会以任何方式修改它,您将无法 write一个const如果您尝试转换为 char* 则对象.

作品:

const emp e1 = {"Abhishek", 22};
fout.write(reinterpret_cast<const char*>(&e1), sizeof e1);

emp e2 = {"Foo", 23};
fout.write(reinterpret_cast<char*>(&e2), sizeof e2);
fout.write(reinterpret_cast<const char*>(&e2), sizeof e2);

甚至无法编译:

const emp e1 = {"Abhishek", 22};
fout.write(reinterpret_cast<char*>(&e1), sizeof e1);

与问题无关但值得注意: 您已硬编码 emp 的大小至24 。不。使用sizeof以获得实际尺寸。即使int在你当前的平台上是4个字节,如果你在不同的平台上编译它可能不是。

与上述相关:如果您希望文件格式在不同平台上工作并照顾 endianness ,请使用固定宽度类型(例如 uint32_t 表示 4 字节无符号整数) - 但仍然使用sizeof ,因为添加/删除成员时手动计算大小很容易导致错误。

关于c++ - `fout.write( reinterpret_cast<const char*>(&e), sizeof(e) );` 为什么在这里转换成 `const char*` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69026869/

相关文章:

c++ - 复制构造函数如何工作?

c++ - 是否可以在 C++11 中指定枚举的位宽?

java - 尝试将二进制文件作为文本读取,但扫描仪在第一行停止

python - 反序列化 Google Protobuf 二进制文件

objective-c - 如何从巨大的文本文件中读取文本 block ?

c++ - C++中的模式匹配风格?

c++ - 创建 GStreamer XUL 元素?

c++ - 在 C++ 2 中读取二进制文件

c - 读取文本文件和 C 中每个单词的大写首字母

ios - 为什么我的 iOS 应用程序没有出现在其他应用程序的 "Open in"对话框中?