reading binary files

I have been reading an array of SRD objects from a binary file - but since this was my first time doing so, I have modified a header making all its members public as I wasn't sure what would be going on. I have completed my assignment, all that is left is to make these members private and write methods that modify them. However, there is a problem. For debugging purposes I put only 1 member private, and until I write all methods for it I will keep it that way. This member is simply an unsigned int C. When writing a method for returning it (getC() returns C), it is returning a value of 0000...3435973836, meaning it is not set? So, I have an array of pointers to SRD created based on the number of objects in the binary file.
1
2
3
SRD *a;
...
a = new SRD[numOfRecords];

and the array is filled from the file...
1
2
3
4
5
6
for (i=0; i<numOfRecords; i++)
    {
        f.seekg(i * sizeof s);  
        f.read((char *)&a[i], sizeof s);
        cout << a[i].getCC();
    }


now, a[i].getCC() works when C is public, but making it private makes 000..3435... meaning accessing it is not the problem, but it is not set in the fread from the previous for loop. I imagine I need some type of assignment operator, that sets these values, but I have no clue...

all I need is a simple example of a 1 member class and how to read from a binary file
I didn't get your problem exactly but want to point at one mistake.a is already a pointer so & is not required while reading.f.read((char *)a[i], sizeof(s));

what is s anyway?
I must disagree with Akshit. & is required because while a is indeed a pointer, a[i] is not. So it's either (char*)&a[i] or (char *)(a + i). However the question "what is s" is very reasonable.

Do you use the same file for reading the data before and after declaring the variable C private? If yes then do you change the order of member declaration (see below)?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class s {
public:
   int A;
   int B;
};

// This is laid out in the same way...
class s {
public:
   int A;
private:
   int B;
};

// ... and this is not
class s {
private:
   int B;
public:
   int A;
};


Also, writing the whole object is not always a good idea - for example if you have virtual functions/virtual base classes this way of persistence is very likely to fail (because virtual functions table and virtual base class table are also parts of the object). If your data is not trivial and/or you want it to be portable - you should either save it manually (member-by-member) or use a library with this purpose, such as boost serialization library: http://www.boost.org/doc/libs/1_50_0/libs/serialization/doc/index.html
Last edited on
Topic archived. No new replies allowed.