我有这个结构:
struct Employee
{
char VarOne[50];
unsigned int VarTwo;
double VarThree[4];
}
然后,我填充此结构的动态数组:
Employee* MyArray = new Employee[TheSize]; // Sorry I forgot to mention TheSize is = 5 constant
然后,我尝试将数组以二进制模式写入文件:
// write as binary
fstream OutFileBin;
OutFileBin.open("Employee.dat", ios::binary | ios::out);
OutFileBin.write(reinterpret_cast<char *>(&MyArray), TheSize * sizeof(Employee));
OutFileBin.close();
但是当我以二进制模式读取文件时,它失败并且数据是垃圾:
// read as binary
fstream InFilebin;
InFilebin.open("Employee.dat", ios::binary | ios::in);
Employee NewArray[TheSize]; // sorry I forgot to mention TheSize is = 5 constant
InFilebin.read(reinterpret_cast<char *>(&NewArray), TheSize * sizeof(Employee));
我做错了什么?
答案 0 :(得分:3)
行
OutFileBin.write(reinterpret_cast<char *>(&MyArray), TheSize * sizeof(Employee));
不好。您不想将&MyArray
视为存储类型为Employee
的对象。它只需是MyArray
。
OutFileBin.write(reinterpret_cast<char*>(MyArray), TheSize * sizeof(Employee));
还
Employee NewArray[TheSize];
除非TheSize
是编译时间常数,否则不是标准C ++。将其更改为
Employee* NewArray = new Employee[TheSize];
以及下面的行
InFilebin.read(reinterpret_cast<char *>(NewArray), TheSize * sizeof(Employee));