代码
#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;
}
为什么需要对write
和read
函数的第一个参数进行reinterpret_cast
?
为什么我们在 write
和 中将
函数?emp
类型的地址特别转换为 const char*
和 char*
code>分别读取
最佳答案
Why it is necessary to do
reinterpret_cast
with 1st argument ofwrite
andread
function ?
因为 write()
的第一个参数是 const char*
和 read()
的第一个参数是 char*
.
why we casting address of type
emp
particularly toconst char*
andchar*
inwrite
andread
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/