为什么保存到文件不能按预期工作?

问题描述 投票:-3回答:1

我有这个结构:

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

我做错了什么?

c++ struct binaryfiles
1个回答
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));
© www.soinside.com 2019 - 2024. All rights reserved.