title: How to use fread and fwrite functions to read and write Binary files?
body: <p>Hi in my project I've to read a .bin file which has sensor data in the form of <code>short(16 bit values)</code>. I'm doing this using <code>fread</code> function into a buffer, but I feel that the reading-in is not happening correctly. I mean <strong>there is no consistence between what I write and what I read in.</strong> Can you guys suggest what is going wrong here? This is not my code from my project... I'm only trying to verify the <code>fread</code> and <code>fwrite</code> functions here.</p>
  
  <pre><code>#include&lt;stdio.h&gt;
  void main()
  {
      FILE *fp = NULL;
  
      short x[10] = {1,2,3,4,5,6,5000,6,-10,11};
      short result[10];
  
      fp=fopen("c:\\temp.bin", "wb");
  
      if(fp != NULL)
      {
          fwrite(x, 2 /*sizeof(short)*/, 10 /*20/2*/, fp);
          rewind(fp);
          fread(result, 2 /*sizeof(short)*/, 10 /*20/2*/, fp);
      }
      else
          exit(0);
  
      printf("\nResult");
      printf("\n%d",result[0]);
      printf("\n%d",result[1]);
      printf("\n%d",result[2]);
      printf("\n%d",result[3]);
      printf("\n%d",result[4]);
      printf("\n%d",result[5]);
      printf("\n%d",result[6]);
      printf("\n%d",result[7]);
      printf("\n%d",result[8]);
      printf("\n%d",result[9]);
  
      fclose(fp)
   }
  </code></pre>
  
  <p>After I do the fread() (HEX values):</p>
  
  <pre><code>temp.bin:
  01 02 03 04 05 06 e1 8e 88 06 ef bf b6 0b...
  </code></pre>
  
  <p>After I do the fwrite()</p>
  
  <pre><code>stdout:
  Result
  0
  914
  -28
  -28714
  -32557
  1
  512
  -32557
  908
  914
  </code></pre>