title: Parsing a binary file. What is a modern way?
body: <p>I have a binary file with some layout I know. For example let format be like this:</p>
  
  <ul>
  <li>2 bytes (unsigned short) - length of a string</li>
  <li>5 bytes (5 x chars) - the string - some id name</li>
  <li>4 bytes (unsigned int) - a stride</li>
  <li>24 bytes (6 x float - 2 strides of 3 floats each) - float data</li>
  </ul>
  
  <p>The file should look like (I added spaces for readability):</p>
  
  <pre><code>5 hello 3 0.0 0.1 0.2 -0.3 -0.4 -0.5
  </code></pre>
  
  <p>Here 5 - is 2 bytes: 0x05 0x00. "hello" - 5 bytes and so on.</p>
  
  <p>Now I want to read this file. Currently I do it so:</p>
  
  <ul>
  <li>load file to <strong>ifstream</strong></li>
  <li>read this stream to <code>char buffer[2]</code> </li>
  <li>cast it to unsigned short: <code>unsigned short len{ *((unsigned short*)buffer) };</code>. Now I have length of a string.</li>
  <li>read a stream to <code>vector&lt;char&gt;</code> and create a <code>std::string</code> from this vector. Now I have string id.</li>
  <li>the same way read next 4 bytes and cast them to unsigned int. Now I have a stride.</li>
  <li>while not end of file read floats the same way - create a <code>char bufferFloat[4]</code> and cast <code>*((float*)bufferFloat)</code> for every float.</li>
  </ul>
  
  <p>This works, but for me it looks ugly. Can I read directly to <code>unsigned short</code> or <code>float</code> or <code>string</code> etc. without <code>char [x]</code> creating? If no, what is the way to cast correctly (I read that style I'm using - is an old style)?</p>
  
  <p>P.S.: while I wrote a question, the more clearer explanation raised in my head - how to cast arbitrary number of bytes from arbitrary position in <code>char [x]</code>?</p>
  
  <p>Update: I forgot to mention explicitly that string and float data length is not known at compile time and is variable.</p>