title: Why am i Getting garbage value when reading a binary file?
body: <p>For the sake of simplicity I wrote a simple code to reproduce my problem. As you can see on the code i created a struct with two members then I created and array of the struct type then initialized it <code>student newStudent[3] ={{&quot;joseph&quot;,20}, {&quot;yonas&quot;,30},{&quot;miryam&quot;,40}};</code>. I stored all the info from the struct to a binary file <code>newFile.write(reinterpret_cast&lt;char*&gt;(newStudent), 3 * sizeof(student));</code>(everything is fine until here) then i created another array <code>student loadedStudent[3];</code> to load into, all the data from the binary file and output the loaded data using a for loop <code>cout&lt;&lt;&quot;Name: &quot;&lt;&lt;loadedStudent[i].name&lt;&lt;&quot;Age: &quot;&lt;&lt;loadedStudent[i].age&lt;&lt;endl;</code>. The problem is that the data i stored is <code>joseph&quot;,20, &quot;yonas&quot;,30,&quot;miryam&quot;,40</code> but the program is outputting garbage values <code>Name: 8H???Age: 1 Name: J???Age: 1 Name: ?I???Age: 32766</code>.
  Why is that?</p>
  <pre><code>#include &lt;iostream&gt;
  #include &lt;fstream&gt;
  
  using namespace std;
  
  struct student{
      char name[10];
      int age;
  };
  
  int main()
  {
      student newStudent[3] ={{&quot;joseph&quot;,20}, {&quot;yonas&quot;,30},{&quot;miryam&quot;,40}};
  
      fstream newFile;
      newFile.open(&quot;/Users/josephfeleke/Desktop/abeltest/file.bin&quot;, ios::out | ios::binary);
  
  //for(int i = 0; i&lt;3; i++){
          //cout&lt;&lt;&quot;Name: &quot;&lt;&lt;newStudent[i].name&lt;&lt;&quot; Age: &quot;&lt;&lt;newStudent[i].age&lt;&lt;endl;
      //}
  
      if(newFile.is_open()){
  
         newFile.write(reinterpret_cast&lt;char*&gt;(newStudent), 3 * sizeof(student));
  
      }else cout&lt;&lt;&quot;faild to open file&quot;;
     
      student loadedStudent[3];
      newFile.seekg(0, ios::beg);
  
      if(newFile.is_open()){
  
         newFile.read(reinterpret_cast&lt;char*&gt;(loadedStudent), 3 * sizeof(student));
         newFile.close();
  
      }else cout&lt;&lt;&quot;faild to open file&quot;;
  
      for(int i = 0; i&lt;3; i++){
  
          cout&lt;&lt;&quot;Name: &quot;&lt;&lt;loadedStudent[i].name&lt;&lt;&quot;Age: &quot;&lt;&lt;loadedStudent[i].age&lt;&lt;endl;
      }
  </code></pre>