0
struct ID3v2_header{
  char tag[3];
  char ver[2];
  char flag;
  int size;
 };


ID3v2_header readID3v2_head(string file){
  char buf[10];
  ifstream infile(file.c_str(),ios::binary);
  ID3v2_header head;
  if(!infile || !infile.read(buf, 10)){
     cout<<"FAIL"<<endl;
     infile.close();
     return head;
   }
   memcpy(&head,buf,10);
   infile.close();
   return head;

  }

I just output the size after and it changes every time I run, am I overflowing somewhere?

carboncomputed
  • 1,630
  • 3
  • 20
  • 42
  • What he said. Also, was the file written from the same structure, using the same compiler with the same settings? – Mr Lister Mar 18 '12 at 21:18
  • 1
    You should go back and read the answers to [your other question](http://stackoverflow.com/questions/9696308/why-is-the-size-of-this-struct-12-and-not-10). – Blastfurnace Mar 18 '12 at 21:19

2 Answers2

3

You should check your assumption that sizeof(ID3v2_header) == 10.

You should then fill out the fields of the struct manually, rather than by using memcpy.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • sizeof results in 12 but I thought it was because of byte alignment. http://stackoverflow.com/questions/9696308/why-is-the-size-of-this-struct-12-and-not-10 – carboncomputed Mar 18 '12 at 21:20
  • That is correct. Unfortunately for you, the alignment occurs before the field `size` (since it is at offset 6, more that likely it is pushed to offset 8). – vhallac Mar 18 '12 at 21:24
  • Ok I think I'm understanding, if I were to go through each of the fields manually, would I be able to solve the issue? – carboncomputed Mar 18 '12 at 21:29
  • @user979663: When reading complex structures from disk, you always need to deal with differences in alignment, and endianness. So you should do something stuff like `head.size = readInt(&buf[6]);`, where `readInt` is something like `int readInt(const char *x) { return x[0] | (x[1] << 8) | (x[2] << 16) | (x[3] << 24); }` (or vice versa, depending on the endianness. – Oliver Charlesworth Mar 18 '12 at 21:35
  • That also means that if you are designing the file format, you need to decide on the alignment and endianness for the file format. – David Schwartz Mar 18 '12 at 23:53
0

A file is a stream of bytes. Before you write data to a file, you need to convert it into a stream of bytes with a known format. When you read that data back from the file, you need to convert from the format of that stream of bytes to the format of your structures in memory.

memcpy(&head,buf,10);

This doesn't work because head is in a memory format and buf is in a file format. You need some code to convert between these two different formats.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278