title: Reading\Writing Structured Binary File in C++
body: <p>i want to read\write a binary file which has the following structure:</p>
  
  <p><img src="https://i.stack.imgur.com/mMhyD.jpg" alt="enter image description here"></p>
  
  <p>The file is composed by "RECORDS". Each "RECORD" has the following structure: I will use the first record as example</p>
  
  <ul>
  <li>(red)START byte: 0x5A (always 1 byte, fixed value 0x5A)</li>
  <li>(green) LENGTH bytes: 0x00 0x16 (always 2 bytes, value can change
  from "0x00 0x02" to "0xFF 0xFF")</li>
  <li>(blue) CONTENT: Number of Bytes indicated by the decimal value of
  LENGTH Field minus 2.</li>
  </ul>
  
  <p>In this case LENGHT field value is 22 (0x00 0x16 converted to decimal), therefore the CONTENT will contain 20 (22 - 2) bytes.
  My goal is to read each record one by one, and write it to an output file. Actually i have a read function and write function (some pseudocode):</p>
  
  <pre><code>private void Read(BinaryReader binaryReader, BinaryWriter binaryWriter)
  {
      byte START = 0x5A;
      int decimalLenght = 0;
      byte[] content = null;
      byte[] length = new byte[2];
  
      while (binaryReader.PeekChar() != -1)
      {
          //Check the first byte which should be equals to 0x5A
          if (binaryReader.ReadByte() != START)
          {
              throw new Exception("0x5A Expected");
          }
  
          //Extract the length field value
          length = binaryReader.ReadBytes(2);
  
          //Convert the length field to decimal
          int decimalLenght = GetLength(length);
  
          //Extract the content field value
          content = binaryReader.ReadBytes(decimalLenght - 2);
  
          //DO WORK
          //modifying the content
  
          //Writing the record
          Write(binaryWriter, content, length, START);
      }
  }
  
  private void Write(BinaryWriter binaryWriter, byte[] content, byte[] length, byte START)
  {
      binaryWriter.Write(START);
      binaryWriter.Write(length);
      binaryWriter.Write(content);   
  }
  </code></pre>
  
  <p>As you can see i have already write it for C#, but i don't really know how to it with C++.
  Can someone please point me in the right direction ?</p>