I would like to read a binary file that has a number of class P objects, and one of the members is an array of struct C objects:
class P
{
protected:
double n[5];
C Cs[5];
};
struct C
{
int S;
char Name[20];
};
and I have no idea how to do this, i went thru some examples and they are for reading videos/images...
i know how to get the number P objects, but i dont know how to construct them using the data from the file...
// read a file into memory
#include <iostream>
#include <fstream>
usingnamespace std;
struct C
{
int S;
char Name[20]
};
int main () {
C InputStruct;
ifstream is;
is.open ("test.txt", ios::binary );
// read data as a block:
is.read ( &InputStruct, sizeof(InputStruct) );
is.close();
return 0;
}
i know how to do this, but the problem is reading class objects - are the objects already "constructed" inside the file, and all i do is assign them to an array of objets - or does the binary file contain only data, so i get these parameters and construct the objects?
and also i need to create the array of C structures within each P
if i have P temp;
is it possible that all i need to do is use seekg for 0 to number of P objects, each time using f.read ( &temp, sizeof(temp) ) and then copying temp into an array of P objets, while of course overloading the assignment operator so that any pointers dont point to the actual text file but to newly allocated memory where the members are copied?
Ok, let's say the file uses this structure:
1st 4 bytes contain an integer with how many C structs are there,
2nd 4 bytes contain an integer with how many P classes are there,
// read a file into memory
#include <fstream>
usingnamespace std;
class P
{
protected:
double n[5];
C Cs[5];
};
struct C
{
int S;
char Name[20]
};
int main () {
C* InputStructs;
P* InputClasses;
int NumClasses;
int NumStructs;
ifstream is;
is.open ("test.txt", ios::binary );
// Get the number of objects to read
is.read ( (char*)&NumStructs, sizeof(NumStructs) );
is.read ( (char*)&NumClasses, sizeof(NumClasses) );
// Allocate the applicable amount of memory:
InputStructs = new C[NumStructs];
InputClasses = new P[NumClasses];
// Option 1, read them one at a time:
for (int i = 0; i < NumStructs; ++i)
is.read ( (char*)&InputStructs[i], sizeof(InputStructs[i]) );
for (int i = 0; i < NumClasses; ++i)
is.read ( (char*)&InputClasses[i], sizeof(InputClasses[i]) );
// Option 2, read large bulk
is.read ( (char*)InputStructs, sizeof(InputStructs[0]) * NumStructs);
is.read ( (char*)InputClasses, sizeof(InputClasses[0]) * NumClasses);
is.close();
return 0;
}
Edit: I'm reading disch's post in ne555's link. It makes sense and would probably be a more professional solution.