title: Reading a structure from a binary file in c++
body: <p>So I'm trying to read a structure from a binary file that I write but something seems to be wrong. Here is my main:</p>
  
  <pre><code>//Fraction structure
  struct Fraction
  {
  int num, den;
  };
  
  
  int main()
  {
  int menu_selection;
  char slash;
  
  fstream datafile; //creates file object
  Fraction* f; //creates pointer for dam
  
  //menu to the user
  menu_selection = main_menu();
  bool condition = true;
  while (condition)
  {
      switch(menu_selection)
      {
      case 1: //adds a new Fraction structure to binary file
          f = new Fraction; //dynamically allocating memory
          cout &lt;&lt; "Enter fraction to add: "; //adds fraction to file
          cin &gt;&gt; f-&gt;num &gt;&gt; slash &gt;&gt; f-&gt;den;//stores input
          datafile.open("fractions.dat",ios:: out | ios:: app | ios::binary); //creates file
          datafile.write(reinterpret_cast&lt;char *&gt;(f),sizeof(Fraction));//stores fraction to file
          datafile.close();
          menu_selection = main_menu();
          break;
      case 2:
          menu_selection = main_menu();
          break;
      case 3: //displays the contents of the file to user
          datafile.open("fractions.dat", ios::in | ios::binary);
          while(!datafile.eof())
          {
              datafile.read(reinterpret_cast&lt;char *&gt;(f),sizeof(f));
              cout &lt;&lt; f-&gt;num &lt;&lt; "/" &lt;&lt; f-&gt;den &lt;&lt; " ";
          }
          datafile.close();
          menu_selection = main_menu();
          break;
      case 4:
          menu_selection = main_menu();
          break;
      case 5:
          menu_selection = main_menu();
          break;
      case 6: condition = false;
          return 0;
          break;
      default: cout &lt;&lt; endl &lt;&lt; "That is an invalid option. Please try again." &lt;&lt; endl; //default option
          break;
      }
  }
  delete f;
  }
  </code></pre>
  
  <p>When the user enters 1 I dynamically allocate memory for the structure Fraction and writes it to a binary file. I use ios::app because I want to add on to the file when it is called again. Is there anything wrong with either the writing or the reading functions? Whenever I run the program as it is, if I input one fraction such as 1/5, it shows 1/5 5/5 5/5, however if I input two fractions such as 1/5 and 2/6, it shows 2/6 6/6 6/6.</p>