为什么保存到文件无法按预期工作?

时间:2019-03-20 17:51:03

标签: c++ struct binaryfiles

我有这个结构:

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

我做错了什么?

1 个答案:

答案 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));