0

I'm using the code below to read a struct from a binary file.

struct A
{
  int s;
  char cname[20];
};

int main () {
  A mystruct;

  ifstream is;
  is.open ("filename.txt", ios::binary );

  is.read ( &mystruct, sizeof(InpumystructtStruct) );
  is.close();

  return 0;
}

Suppose there are multiple structs in the binary file, of type struct A, struct B and struct C, with different size appearing in the file. If I want to read all of them in sequence, assuming I know the sequence, would this be correct?

struct A
{
  int s;
  char cname[20];
};
struct B
{
  int s;
};    
struct A
{
  char cname[20];
};

int main () {
  A mystructa;
  B mystructb;
  C mystructc;

  ifstream is;
  is.open ("filename.txt", ios::binary );

  while( is.good()  ) {
      // determine struct to use 
      is.read ( &mystruct/*put right type*/, sizeof(/*put right tupe*/) );
  }
  is.close();

  return 0;
}

1 Answer 1

1

No, that won't work.

If you know they were written sequentially in the file:

struct {
     A a;
     B b;
     C c;
} v;

is.read (&v, sizeof v);

However, this has many problems. Not the least of which is that there could be structure padding, size of int used by the writer, endian problems, etc.

These sorts of concerns are all addressed by universal data formats such as JSON, XML, etc.

Slightly more portably, this variation of what you wrote would work, though with the same problems as before:

A mystructa;
B mystructb;
C mystructc;

is.read (&mystructa, sizeof mystructa);
is.read (&mystructb, sizeof mystructb);
is.read (&mystructc, sizeof mystructc);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.