title: Reading Binary files in C++ 2
body: <p>I had just started with binary files. I tried out a simple programme:</p>
  
  <pre><code>class student
  {
      int rno;
      char sname[20];
      public:
      void input();
      void output();
  };
  
  void main() 
  {
      clrscr();
      student s;
      char reply;
      fstream fil;
  
      fil.open("stu.dat",ios::binary|ios::app);
      do
      {
          s.input();
          fil.write((char*)&amp;s,sizeof(s));
          cout&lt;&lt;"more (Y/N)\n";
          cin&gt;&gt;reply;
      }
      while(toupper(reply)=='Y');
      fil.close();
  }
  
   void  student::input()
   {
   cout&lt;&lt;"enter the roll\n";
   cin&gt;&gt;rno;
   cout&lt;&lt;endl;
   cout&lt;&lt;"enter the name\n";
   gets(sname);
   cout&lt;&lt;endl;
   }
  
   void  student::output()  
   { 
   cout&lt;&lt;" the roll\n";
   cout&lt;&lt;rno;
   cout&lt;&lt;endl;
   cout&lt;&lt;"the name\n";
   puts(sname);
   cout&lt;&lt;endl;
  </code></pre>
  
  <p>But when i read this (say i have added 3 students) only last student's details are shown. why?
  Reading code:</p>
  
  <pre><code>  #include&lt;fstream.h&gt;
    #include&lt;conio.h&gt;
    #include&lt;stdio.h&gt;
    #include&lt;ctype.h&gt;
  
    class student
    {
    int rno;
    char sname[20];
    public:
    void input();
    void output();
    };
  
    void main()
    {
    clrscr();
    student s;
    fstream fil;
    fil.open("stu.dat",ios::binary|ios::in);
  
    while(fil.read((char*)&amp;s,sizeof(s)));
    {
    s.output();
    getch();
    }
    fil.close();  
    }  
  
    void  student::input()
    {
    cout&lt;&lt;"enter the roll\n";
    cin&gt;&gt;rno;
    cout&lt;&lt;endl;
    cout&lt;&lt;"enter the name\n";
    gets(sname);
    cout&lt;&lt;endl;
    }
  
    void  student::output()
    {
    cout&lt;&lt;" the roll\n";
    cout&lt;&lt;rno;
    cout&lt;&lt;endl;
    cout&lt;&lt;"the name\n";
    puts(sname);
    cout&lt;&lt;endl;
    } 
  </code></pre>
  
  <p>But when i read this (say i have added 3 students) only last student's details are shown. why?</p>
  
  <p>Where am i going wrong?</p>