Search code examples
c++structbinaryfiles

Why saving to a file is not working as expected?


I have this struct:

struct Employee
{
   char VarOne[50];        
   unsigned int VarTwo;      
   double VarThree[4];           
}

Then, I populate a dynamic array of this struct:

 Employee* MyArray = new Employee[TheSize]; // Sorry I forgot to mention TheSize is = 5 constant

Then, I try and write the array in binary mode to a file:

   // write as binary
   fstream OutFileBin;
   OutFileBin.open("Employee.dat", ios::binary | ios::out);
   OutFileBin.write(reinterpret_cast<char *>(&MyArray), TheSize * sizeof(Employee));
   OutFileBin.close();

But when I read the file in binary mode, it fails and data are junk:

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

What is that I am doing wrong?


Solution

  • The line

    OutFileBin.write(reinterpret_cast<char *>(&MyArray), TheSize * sizeof(Employee));
    

    is not good. You don't want to treat &MyArray as though it stores objects of type Employee. It needs to be just MyArray.

    OutFileBin.write(reinterpret_cast<char*>(MyArray), TheSize * sizeof(Employee));
    

    Also,

    Employee NewArray[TheSize];
    

    is not standard C++ unless TheSize is a compile time constant. Change it to

    Employee* NewArray = new Employee[TheSize];
    

    and the following line to

    InFilebin.read(reinterpret_cast<char *>(NewArray), TheSize * sizeof(Employee));